第一種方法
直接在子組件中通過this.$parent.event來調用父組件的方法
父組件
<template> <div> <child></child> </div> </template> <script> import child from './components/dam/child'; export default { components: { child }, methods: { fatherMethod() { console.log('測試'); } } }; </script>
子組件
<template> <div> <button @click="childMethod()">點擊</button> </div> </template> <script> export default { methods: { childMethod() { this.$parent.fatherMethod(); } } }; </script>
第二種方法
在子組件里用$emit
向父組件觸發一個事件,父組件監聽這個事件就行了。
父組件
<template> <div> <child @fatherMethod="fatherMethod"></child> </div> </template> <script> import child from '~/components/dam/child'; export default { components: { child }, methods: { fatherMethod() { console.log('測試'); } } }; </script>
子組件
<template> <div> <button @click="childMethod()">點擊</button> </div> </template> <script> export default { methods: { childMethod() { this.$emit('fatherMethod'); } } }; </script>
第三種方法
父組件把方法傳入子組件中,在子組件里直接調用這個方法
父組件
<template> <div> <child :fatherMethod="fatherMethod"></child> </div> </template> <script> import child from '~/components/dam/child'; export default { components: { child }, methods: { fatherMethod() { console.log('測試'); } } }; </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(); } } } }; </script>
子組件 更簡便的寫法
<template> <div> <button @click="fatherMethod()">點擊</button> </div> </template> <script> export default { props: { fatherMethod: { type: Function, default: null } }, methods: { } }; </script>