第一種(與v-model做的事情相同)
特別注意:value必須都是小寫
父組件:<son :value="value" @getValue="getValue">
getValue (value) {
console.log(value)
}
子組件:
props: ['value'] // 接收父組件傳遞的值
emits:['getValue']
transValue () {
this.$emit('getValue',this.data.value) // 觸發(fā)父組件事件
}
父組件:<gao ref="box" ></gao>
this.$refs.box.getValue(params)
子組件:getValue(params){console.log(params)}
// 父組件
<child :value.sync="inputVal"></child>
// 子組件
<div> {{_val}} </div>
props: {value: String}
this._val = '111'
computed: {
_val : {
get () {
return this.value
},
// 觸發(fā)改變父組件的值
set (newVal) {
this.$emit('update:value',newVal)}
}
}
// eventBus.js中
export default new Vue()
// in component A
import bus from './eventBus.js'
bus.$emit('plus', 1)
bus.$emit('minus', 1)
// in component B's created hooks
import bus from './eventBus.js'
bus.$on('plus', function (n) {
this.total += n
})
bus.$on('minus', function (n) {
this.total -= n
})
// clear in hooks
beforeDestroy(){
bus.$off('click')
}
// 祖先組件,作為一個鉤子函數(shù),返回一個對象供子組件使用
provide() {
return {
name: 'xxx',
fn () {},
}
}
// 子孫組件
接收屬性或方法
inject:['name','fn']
// 父組件中,$children是個數(shù)組
this.$children[0].msg
// 子組件中,$parent是個對象
this.$parent.name
組件的inheritAttrs屬性默認(rèn)為true,繼承所有的父組件(除props之外)的所有屬性;
inheritAttrs:false 只繼承class屬性 。
abc組件的關(guān)系為,a包含b,b包含c,現(xiàn)在要c獲取a的屬性或者監(jiān)聽器
// a組件
<child1 :p-child1="child1" :p-child2="child2" :name="name" :age="age" @test1="onTest1" @test2="onTest2"></child1>
// b組件
<child2 v-bind="$attrs" v-on="$listeners"></child2>
props: ['pChild1'],
inheritAttrs: false, // 不繼承
this.$emit('test1');
// c組件
props: [ 'name']
觸發(fā)
this.$emit('test1');
this.$emit('test2');
獲取
$attrs // 只有 p-child2、age,因為p-child1、name 為已在組件中聲明的props
this.pChild2
this.age
最后編輯于 :2022.11.15 18:20:09
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者 【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。 平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。