VUE子組件向父組件傳值詳解(含傳多值及添加額外參數場景)
一、子組件向父組件傳遞一個值
子組件:
this.$emit('change', this.value);
父組件:
<!-- 在父組件中使用子組件 --> <editable-cell :text="text" :inputType="inputType" @change="costPlannedAmountChange($event)" />
// 事件處理函數
async costPlannedAmountChange(value) {
console.log(value)
}
在使用子組件時,綁定change函數的事件處理函數也可以寫成如下格式:
<editable-cell :text="text" :inputType="inputType" @change="costPlannedAmountChange" />
綁定事件處理函數時,可以不帶括號,形參則默認為事件對象,如果綁定時帶上了括號,再想使用事件對象則需要傳入$event作為實參。
二、子組件向父組件傳遞一個值,并攜帶額外參數
record為額外參數( 本文的額外參數都拿record做舉例 )。
子組件:
this.$emit('change', this.value);
父組件:
<!-- 插槽 --> <template slot="planned_amount" slot-scope="text, record"> <!-- 在父組件中使用子組件 --> <editable-cell :text="text" :inputType="inputType" @change="costPlannedAmountChange(record,$event)" /> </template>
// 事件處理函數
async costPlannedAmountChange(record,value) {
console.log(record,value)
},
綁定事件處理函數時,record和$event的順序不做要求,但是按照vue事件綁定的習慣,$event通常放在實參列表末尾。
三、子組件向父組件傳遞多個值
子組件:
// 向父組件傳遞了兩個值
this.$emit('change', this.value,this.text);
父組件:
<editable-cell :text="text" :inputType="inputType" @change="costPlannedAmountChange" />
// 事件處理函數
async costPlannedAmountChange(param1,param2) {
console.log(param1,param2)
},
綁定事件處理函數時,不能攜帶括號?。。∪绻麛y帶括號并且在括號內加了$event,只能拿到子組件傳遞過來的第一個參數。
四、子組件向父組件傳遞多個值,并攜帶額外參數
record為額外參數( 本文的額外參數都拿record做舉例 )。
子組件:
// 向父組件傳遞了兩個值
this.$emit('change', this.value,this.text);
父組件:
<template slot="planned_amount" slot-scope="text, record"> <!-- 在父組件中使用子組件 --> <editable-cell :text="text" :inputType="inputType" @change="costPlannedAmountChange(record,arguments)" /> </template>
// 事件處理函數
async costPlannedAmountChange(record,args) {
console.log(record,args)
},
arguments是方法綁定中的一個關鍵字,內部包括了所有方法觸發(fā)時傳遞過來的實參。arguments和額外參數的位置誰先誰后不做要求,建議arguments放后面。
查看args的打印結果:

總結
到此這篇關于VUE子組件向父組件傳值(含傳多值及添加額外參數場景)的文章就介紹到這了,更多相關VUE子組件向父組件傳值內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
vue本地構建熱更新卡頓的問題“75?advanced?module?optimization”完美解決方案
這篇文章主要介紹了vue本地構建熱更新卡頓的問題“75?advanced?module?optimization”解決方案,每次熱更新都會卡在?"75?advanced?module?optimization"?的地方不動了,如何解決這個問題呢,下面小編給大家?guī)砹私鉀Q方案,需要的朋友可以參考下2022-08-08

