Vue子元件呼叫父元件的方法
阿新 • • 發佈:2020-08-18
Vue中子元件呼叫父元件的方法,這裡有三種方法提供參考
父元件
<template>
<div>
<child></child>
</div>
</template>
<script>
import child from '~/components/dam/child';
export default {
components: {
child
},
methods: {
fatherMethod() {
console.log('測試 ');
}
}
};
</script>
第一種方法:直接在子元件中通過this.$parent.event來呼叫父元件的方法
子元件
<template> <div> <button @click="childMethod()">點選</button> </div> </template> <script> export default { methods: { childMethod() { this.$parent.fatherMethod(); } } };</script>
第二種方法:在子元件裡用$emit
向父元件觸發一個事件,父元件監聽這個事件就行了。
子元件
<template> <div> <button @click="childMethod()">點選</button> </div> </template> <script> export default { methods: { childMethod() { this.$emit('fatherMethod'); } } };</script>
第三種方法:父元件把方法傳入子元件中,在子元件裡直接呼叫這個方法
子元件
<template> <div> <button @click="childMethod()">點選</button> </div> </template> <script> export default { props: { fatherMethod: { type: Function, default: null } }, methods: { childMethod() { if (this.fatherMethod) { this.fatherMethod(); } } } };