很多時候,可能需要子元件去調用父元件的方法,之前寫過《Vue依賴注入(provide/inject)》,裡面有調用父元件方法,這次總結三種方法,相當于有四種方法!
第一種:子元件中通過this.$parent.event來調用父元件的方法
注意:使用此方法,層級很重要!
父元件:
import child from '~/components/dam/child';
export default {
components: {
child
},
methods: {
fatherMethod() {
console.log('測試');
}
}
};
子元件
點選
export default {
methods: {
childMethod() {
this.$parent.fatherMethod();
}
}
};
第二種:在子元件裡用$emit向父元件觸發一個事件,父元件監聽這個事件
關于$emit,《Vue父子元件間通信執行個體講解》這裡做了詳細的講解,這裡隻展示代碼,不做過多的說明!
父元件
import child from '~/components/dam/child';
export default {
components: {
child
},
methods: {
fatherMethod() {
console.log('測試');
}
}
};
子元件
點選
export default {
methods: {
childMethod() {
this.$emit('fatherMethod');
}
}
};
第三種:父元件把方法傳入子元件中,在子元件裡直接調用這個方法
父元件
import child from '~/components/dam/child';
export default {
components: {
child
},
methods: {
fatherMethod() {
console.log('測試');
}
}
};
子元件
點選
export default {
props: {
fatherMethod: {
type: Function,
default: null
}
},
methods: {
childMethod() {
if (this.fatherMethod) {
this.fatherMethod();
}
}
}
};
第一種,使用時注意層級問題,不太推薦,推薦第二種方案。