1.父組件的provide和子組件的inject (https://cn.vuejs.org/v2/api/#provide-inject)
-
-
provide
和inject
主要在開發高階插件/組件庫時使用。並不推薦用於普通應用程序代碼中。
2.通過調用this.$parent來調用父級的方法 (https://cn.vuejs.org/v2/api/#vm-parent)
-
在子組件里面 this.$parent 得到的是父組件的實例
3.子組件對外emit一個方法(https://cn.vuejs.org/v2/api/#vm-emit)
-
子組件先執行自己事件,然后在事件里面通過$emit來實現在父組件中調用接收的函數;
4.props來接收父組件傳入的方法
5.四種方法的實現例子如下:
//子組件 <template> <div> <!-- 1.通過provide和inject來實現子調用父方法 --> <span @click="clickFn(1)">click 1.通過provide和inject來實現子調用父方法</span> <br> <!-- 2.通過調用this.$parent來調用父級的方法 --> <span @click="test2">click 2.通過調用this.$parent來調用父級的方法</span> <br> <!-- 3.通過$emit來實現實際調用父級的方法 --> <span @click="test3">click 3.通過$emit來實現實際調用父級的方法</span> <br> <!-- 4.通過props來接收父組件傳入的方法 --> <span @click="test4(4)">click 4.通過props來接收父組件傳入的方法</span> </div> </template> <script> export default { inject:['clickFn'], props:{ test4:{ type:Function, default(){ return function(){} } } }, methods:{ test2(){ this.$parent.toAlert(2) }, test3(){ this.$emit("test3") } } } </script> // 父組件 <template> <div> <child @test3="toAlert(3)" :test4="toAlert" /> </div> </template> <script> import Child from './child' export default { // provide:{ //如果是對象的類型在里面不能用this會找不到,只有是函數類型才可以 // clickFn:"66" // }, provide(){//在這里對外提供方法,在子孫組件中都可以用這個 return { clickFn:this.toAlert } }, components:{ Child }, methods:{ toAlert(count){ alert(count||1) } } } </script>