关键点: 父组件给子组件动态传参使用v-bind:
属性key(多个单词用下划线拼接) 子组件接收父组件传参参数使用 props
标签,+属性key多个单词用驼峰形式拼接)
子组件定义回调父组件函数 子组件: v-on:change="uploadFile()
父组件: :after-upload=“afterUpload” 然后定一个afterUpload(resp)方法接收子组件传过来的值
<div class="col-sm-10"> <file :text="'上传头像1'" :input-id="'image-upload'" :suffixs="[ ['jpg', 'jpeg', 'png']]" :after-upload="afterUpload"> </file> <script> import File from "../../components/file"; export default { components: {File}, name: "business-teacher", data: function () { }, mounted: function () { }, methods: { afterUpload(resp) { let _this = this let image = resp.content; _this.teacher.image = image } } } </script>
子组件
<template> <div> <button type="button" v-on:click="selectFile()" class="btn btn-white btn-default btn-round"> <i class="ace-icon fa fa-upload"></i> {{ text }} </button> <input class="hidden" type="file" ref="file" v-on:change="uploadFile()" v-bind:id="inputId+'-input'"> </div> </template> <script> export default { name: 'file', props: { text: { default: "上传文件" }, inputId: { default: "file-upload" }, suffixs: { default: [] }, afterUpload: { type: Function, default: null }, }, data: function () { return {} }, methods: { uploadFile() { let _this = this; let formData = new window.FormData(); let file = _this.$refs.file.files[0]; // 判断文件格式 let suffixs = _this.suffixs; let fileName = file.name; let suffix = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length).toLowerCase(); let validateSuffix = false; for (let i = 0; i < suffixs.length; i++) { let suffix2 = suffixs[i] += '' if (suffix2.toLowerCase() === suffix) { validateSuffix = true; break; } } if (!validateSuffix) { Toast.warning("文件格式不正确,只支持上传:" + suffixs.join(",")); //解决 同一个文件上传2次或者大于2次,不会发生变化 $("#" + _this.inputId + "-input").val(""); return } // key:"file"必须和后端controller参数名一致 formData.append("file", file); Loading.show() _this.$api.post(process.env.VUE_APP_SERVER + '/file/admin/upload', formData).then((response) => { Loading.hide() let resp = response.data console.log("上传文件成功:", resp) //回调父组件函数 _this.afterUpload(resp) //解决 同一个文件上传2次或者大于3次,不会发生变化 $("#" + _this.inputId + "-input").val(""); }) }, selectFile() { let _this = this // console.log("_this.inputId",_this.inputId) $("#" + _this.inputId + "-input").trigger("click"); } }, } </script> <style scoped> </style>
原文地址:https://gblfy.blog.csdn.net/article/details/121184402
版权声明:除特别声明外,本站所有文章皆是本站原创,转载请以超链接形式注明出处!