前面的话
有时候需要父组件访问子组件,子组件访问父组件,或者是子组件访问根组件。 在组件实例中,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>
新闻热点
疑难解答
图片精选