關于Vue父子組件傳參和回調函數(shù)的使用
關鍵點: 父組件給子組件動態(tài)傳參使用v-bind:屬性key(多個單詞用下劃線拼接) 子組件接收父組件傳參參數(shù)使用 props標簽,+屬性key多個單詞用駝峰形式拼接)
子組件定義回調父組件函數(shù) 子組件: 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次,不會發(fā)生變化
$("#" + _this.inputId + "-input").val("");
return
}
// key:"file"必須和后端controller參數(shù)名一致
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)
//回調父組件函數(shù)
_this.afterUpload(resp)
//解決 同一個文件上傳2次或者大于3次,不會發(fā)生變化
$("#" + _this.inputId + "-input").val("");
})
},
selectFile() {
let _this = this
// console.log("_this.inputId",_this.inputId)
$("#" + _this.inputId + "-input").trigger("click");
}
},
}
</script>
<style scoped>
</style>到此這篇關于關于Vue父子組件傳參和回調函數(shù)的使用的文章就介紹到這了,更多相關Vue父子組件回調函數(shù)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
詳解vue axios用post提交的數(shù)據(jù)格式
這篇文章主要介紹了詳解vue axios用post提交的數(shù)據(jù)格式,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-08-08

