原文地址html
父組件git
<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
向父組件觸發一個事件,父組件監聽這個事件就好了。父組件this
<template> <div> <child @fatherMethod="fatherMethod"></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.$emit('fatherMethod'); } } }; </script>
父組件code
<template> <div> <child :fatherMethod="fatherMethod"></child> </div> </template> <script> import child from '~/components/dam/child'; export default { components: { child }, methods: { fatherMethod() { console.log('測試'); } } }; </script>
子組件component
<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>
$emit能夠調用父組件在子組件身上自定義的事件,須要用@前綴。建議使用此種方式
三種均可以實現子組件調用父組件的方法,可是效率有所不一樣,根據實際需求選擇合適的方法,嗯,就醬~router