1、上代碼:
(1)祖父級組件parent的代碼:
<!-- 文件描述:祖先級組件 創建時間:2019/12/28 15:30 --> <template> <div class="" style="width: 900px;height: 600px;background-color: #d6e7ff;padding: 20px;"> <span style="font-size: 20px;font-weight: bold;">祖先級組件:father</span> <br> 傳給孫子級組件G的參數【toGdata】:{{toGdata}}<br> <input type="text" v-model="toGdata.name"> <div> <childrenA></childrenA> <childrenB></childrenB> <childrenC></childrenC> </div> </div> </template> <script> // 這里可以導入其他文件(比如:組件,工具js,第三方插件js,json文件,圖片文件等等) // 例如:import 《組件名稱》 from '《組件路徑》'; import childrenA from './childrenA' import childrenB from './childrenB' import childrenC from './childrenC' export default { name: 'father', provide () { return { toGdata: this.toGdata } }, // import引入的組件需要注入到對象中才能使用 components: { childrenA, childrenB, childrenC }, data () { // 這里存放數據 return { toGdata: { name: '李四' } } } } </script>
(2)兒子級組件C的代碼:
<template> <div class="" style="float: left;margin: 10px;width: 250px;height: 500px;background-color: #eeff85;padding: 20px;"> <span style="font-size: 18px;font-weight: bold;">兒子級組件C:childrenC</span> <div> <childrenF></childrenF> <childrenG></childrenG> </div> </div> </template>
(3) 孫子級組件G的代碼:
<!--文件描述:孫子級組件G 創建時間:2019/12/28 15:37--> <template> <div class="" style="float: left;margin: 10px;width: 200px;height: 200px;background-color: #ff00de;padding: 20px;color:#fff;"> <span style="font-size: 14px;font-weight: bold;color:#fff;">孫子級組件G:childrenG</span> <div style="color:#0009ff;"> 接受來自祖父級組件parent的數據【toGdata】:{{toGdata}} <input type="text" v-model="fromParentData.name"> </div> </div> </template> <script> export default { name: 'childrenA', inject: ['toGdata'], // import引入的組件需要注入到對象中才能使用 components: {}, data () { // 這里存放數據 return { fromParentData: this.toGdata } } } </script>
注意: 這里不論子組件嵌套有多深, 只要調用了 inject
那么就可以注入 provide
中的數據,而不局限於只能從當前父組件的props屬性中回去數據
2、傳遞參數為值類型(基本類型),接受參數的組件中不能進修改,傳遞對象或者數組,可以直接進行修改,並且可以影響祖先級組件
(1)toGdata傳值改為:String,在孫子級組件G中直接修改則報錯:
在祖父級組件parent中直接修改,沒有傳遞到孫子級組件G:
(2)toGdata傳值改為:Object,在孫子級組件G中直接則對應的祖先級組件數據也會受到影響,原因還是堆和棧儲存數據的問題:
3、結論:在簡單的功能模塊,可以通過傳遞對象實現跨級組件通信,復雜的功能模塊不建議使用,因為傳遞的數據,如果其他的兒子級組件,其他兒子級組件的孫子級組件也在使用的話,會造成數據的混亂,甚至無法理解數據是在哪里變化的,排查故障艱難。跨級組件通信可以定義一個中央事件總線(eventBus),但是更復雜的系統,還是建議使用vuex。