前面的話
有時候需要父組件訪問子組件,子組件訪問父組件,或者是子組件訪問根組件。 在組件實例中,Vue提供了相應的屬性,包括$parent、$children、$refs和$root,這些屬性都掛載在組件的this上。本文將詳細介紹Vue組件實例間的直接訪問
$parent
$parent表示父組件的實例,該屬性只讀
下面是一個簡易實例
<div id="example"> <parent-component></parent-component></div><template id="parent-component"> <div class="parent"> <h3>我是父組件</h3> <input v-model="parentMsg"> <p>{{parentMsg}}</p> <child-component></child-component> </div></template><template id="child-component"> <div class="child"> <h3>我是子組件</h3> <p>{{msg}}</p> <button v-on:click="showData">顯示父組件數據</button> </div></template><script>// 注冊Vue.component('parent-component', { template: '#parent-component', data(){ return{ parentMsg:'我是父組件的數據' } }, components:{ 'child-component':{ template:'#child-component', data(){ return{ msg:'' } }, methods:{ showData(){ this.msg = this.$parent.parentMsg; } } } }})// 創建根實例new Vue({ el: '#example'})</script>$root
$root表示當前組件樹的根 Vue 實例。如果當前實例沒有父實例,此實例將會是其自己。該屬性只讀
<div id="example"> <h3>我是根組件</h3> <input v-model="rootMsg"> <p>{{rootMsg}}</p> <parent-component></parent-component></div><template id="parent-component"> <div class="parent"> <h3>我是父組件</h3> <input v-model="parentMsg"> <p>{{parentMsg}}</p> <child-component></child-component> </div></template><template id="child-component"> <div class="child"> <h3>我是子組件</h3> <p> <button v-on:click="showRootData">顯示根組件數據</button><span>{{rootMsg}}</span> </p> <p> <button v-on:click="showParentData">顯示父組件數據</button><span>{{parentMsg}}</span> </p> </div></template><script>// 注冊Vue.component('parent-component', { template: '#parent-component', data(){ return{ parentMsg:'我是父組件的數據' } }, components:{ 'child-component':{ template:'#child-component', data(){ return{ parentMsg:'', rootMsg:'' } }, methods:{ showParentData(){ this.parentMsg = this.$parent.parentMsg; }, showRootData(){ this.rootMsg = this.$root.rootMsg; }, } } }})// 創建根實例new Vue({ el: '#example', data:{ rootMsg:'我是根組件數據' }})</script>
新聞熱點
疑難解答
圖片精選