首页 > 语言 > JavaScript > 正文

Vue组件实例间的直接访问实现代码

2024-05-06 15:12:37
字体:
来源:转载
供稿:网友

前面的话

  有时候需要父组件访问子组件,子组件访问父组件,或者是子组件访问根组件。 在组件实例中,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>            
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选