Vue $root 对象
示例
在子组件中使用 $root
对象,来改变 Vue 应用的根组件中的 'text' 数据属性。
<template>
<div>
<h3>Change Text</h3>
<p>Click the button to toggle the text in the PRE tag of the root component.</p>
<button v-on:click="this.$root.text='Hello!'">Change text in root</button>
</div>
</template>
运行示例 »
更多示例请参见下方。
定义和用法
$root
对象代表整个 Vue 应用根组件的 Vue 实例。
当 $root
对象在根组件中使用时,它仅仅指向该组件本身。
我们可以使用 $root
对象直接从子组件(即使在组件树结构中很深的位置)访问根实例,以调用方法、读取或修改数据属性等。
注意: 建议使用 props/emit 或 provide/inject 来进行 Vue 组件之间的通信,因为具有这些明确定义的通信方式的代码更容易维护。
更多示例
示例
在子组件中使用 $root
对象,来改变根组件中 <p>
标签的颜色,即使该标签在组件树结构中处于多层以上。
<template>
<div>
<h4>Grand Child Component</h4>
<p>Click the button to toggle the color of the P tag in the root component.</p>
<button v-on:click="this.$root.color='lightgreen'">Change color in root</button>
</div>
</template>
运行示例 »
相关页面
Vue 教程:Vue Props
Vue 教程:Vue $emit() Method
Vue 教程:Vue Provide/Inject
Vue Reference: Vue $emit() Method
Vue 参考:Vue $parent 对象