第一種方法是直接在子組件中經過this.$parent.event來調用父組件的方法測試
父組件this
<template> <div> <child></child> </div> </template> <script> import child from '~/components/dam/child'; export default { components: { child }, methods: { fatherMethod() { console.log('測試'); } } }; </script>
子組件spa
<template> <div> <button @click="childMethod()">點擊</button> </div> </template> <script> export default { methods: { childMethod() { this.$parent.fatherMethod(); } } }; </script>
第二種方法是在子組件裏用$emit
向父組件觸發一個事件,父組件監聽這個事件就好了。code
父組件component
<template> <div> <child @fatherMethod="fatherMethod"></child> </div> </template> <script> import child from '~/components/dam/child'; export default { components: { child }, methods: { fatherMethod() { console.log('測試'); } } }; </script>
子組件blog
<template> <div> <button @click="childMethod()">點擊</button> </div> </template> <script> export default { methods: { childMethod() { this.$emit('fatherMethod'); } } }; </script>
第三種是父組件把方法傳入子組件中,在子組件裏直接調用這個方法事件
父組件ip
<template> <div> <child :fatherMethod="fatherMethod"></child> </div> </template> <script> import child from '~/components/dam/child'; export default { components: { child }, methods: { fatherMethod() { console.log('測試'); } } }; </script>
子組件it
<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>