1. 程式人生 > >vue---vue2.x中父組件事件觸發子組件事件

vue---vue2.x中父組件事件觸發子組件事件

是個 nbsp class this child UNC clas edi 傳參

想要用父組件的事件觸發子組件 第一件事情是先找到子組件,有了子組件才能找到想要調用子組件的方法名

一:找到子元素的方法:

  1.$children : 返回是個數組,可以自己輸出看一下 例子:

//調用第一個子組件的bianji1方法
this.$children[0].bianji1();    

  2.$ref:

HTML: 要在標簽中寫入ref
<allFuncsEdit ref="allFuncsEdit"></allFuncsEdit >
this.$refs.allFuncsEdit;

二:父組件的事件

HTML:

<allFuncsEdit ref="allFuncsEdit" ></allFuncsEdit>

父組件事件:四中方法 參數可有可無

bianjiaClick(){
   this.$children[0].bianji(‘參數‘);
   this.$children[0].$emit(bianji,‘參數‘);
   this.$refs.allFuncsEdit.bianji(‘參數‘)
   this.$refs.allFuncsEdit.$emit(‘bianji‘,‘傳參‘);
}

子組件事件

mounted () {
  
this.$on(‘bianji‘,(val)=>{ this.bianji(val); }); }, methods:{ bianji(val){ if(val===‘‘){ console.log(‘父組件點擊事件調用子組件的方法‘) }else{ console.log(val) } } },

vue---vue2.x中父組件事件觸發子組件事件