VUE中,子組件是不能直接訪問父組件的數據(一般來說,當然如果你要破壞原則也是可以),如下<
<body>
<div id="fathercomponent"> <ul> <li v-for="item in fatherdatas">{{item}}</li> <!--父組件可以訪問它自己的數據--> </ul> <child-component></child-component> </div>
</body>
<script type="text/javascript"> Vue.component('child-component', { // template:'<ul><li v-for="item in fatherdatas"></li></ul>'//子組件不能訪問到父組件的數據 }) vm = new Vue({ data: { fatherdatas: [1,2,3,4,5] } }).$mount('#fathercomponent'); </script>
上面代碼 vm實例掛在了id 為fathercomponent 的DIV中,相當於fathercomponent為一個組件了,這個時候我們在其中定義了一個另一個新組件,這個新定義的組件,和原來的組件,即為父子關系,暫且命名為child-component
我們在vm 中定義的數據 fatherdatas,是父組件fathercomponent中的數據,可以直接在父組件中引用,子組件內部是無法訪問到fatherdatas數據的。如果我們需要訪問這個fatherdatas需要通過props屬性來實現,具體如下
<div id="fathercomponent"> <ul> <li v-for="item in fatherdatas">{{item}}</li> <!--正確父組件可以訪問它自己的數據--> </ul> <child-component :dataarr="fatherdatas"></child-component> <!--我們將父組件中的fatherdatas數據傳給子組件中的dataarr--> </div>
Vue.component('child-component', { props: ['dataarr'],//給props添加一個屬性,這個屬性名字是之前在組件標簽中加的 template: '<ul><li v-for="item in dataarr">{{item}}</li></ul>' //這個時候父組件中的fatherdatas 已經傳遞給了當前組件的dataarr,這樣就可以訪問了 }) vm = new Vue({ data: { fatherdatas: [1,2,3,4,5] } }).$mount('#fathercomponent');
父組件傳遞給子組件,是按值傳遞,因為此時的值是一個對象地址,所以不管是改子組件中的dataarr,還是改父組件fatherdatas,都會影響到另一方,如下
<div id="fathercomponent"> <ul> <li v-for="item in fatherdatas">{{item}}</li> <!--正確父組件可以訪問它自己的數據--> </ul> <child-component :dataarr="fatherdatas" @father="getfatherdatas"></child-component> <!--我們將父組件中的fatherdatas數據傳給子組件中的dataarr--> </div> <!--定義一個father事件-->
Vue.component('child-component', { props: ['dataarr'],//給props添加一個屬性,這個屬性名字是之前在組件標簽中加的 template: '<ul><li v-for="item in dataarr">{{item}}</li></ul>', //這個時候父組件中的fatherdatas 已經傳遞給了當前組件的dataarr,這樣就可以訪問了 created: function () { this.dataarr.push(6);//子組件中的dataarr 添加一個數組元素 this.$emit('father');//觸發組件的father事件 } }) vm = new Vue({ methods: { getfatherdatas() { console.log(this.fatherdatas.join(','));//輸出1,2,3,4,5,6 } }, data: { fatherdatas: [1,2,3,4,5] } }).$mount('#fathercomponent');