Vue $parent 对象
示例
在子组件中使用 $parent
对象,以更改父组件中的 'text' 数据属性。
<template>
<div>
<h3>Change Text</h3>
<p>Click the button to toggle the text in the PRE tag of the parent component.</p>
<button v-on:click="this.$parent.text='Hello!'">Change text in parent</button>
</div>
</template>
运行示例 »
更多示例请参见下方。
定义和用法
$parent
对象表示父组件的 Vue 实例。
如果在根组件中使用 $parent
对象,则 $parent
对象的值将为 null
。
我们可以使用 $parent
对象直接从子组件访问父实例,以调用方法、读取或操作数据属性等。
注意:请考虑使用 props/emit 或 provide/inject 在 Vue 组件之间进行通信,因为使用这些明确定义的通信方式的代码更易于维护。
更多示例
示例
在子组件中使用 $parent
对象,以引用父组件中的方法。
<template>
<div>
<h3>Toggle Color</h3>
<p>Click the button to toggle the color in the P tag of the parent component.</p>
<button v-on:click="this.$parent.toggleColor">Toggle</button>
<p>The 'toggleColor' method is also in the parent component.</p>
</div>
</template>
运行示例 »
相关页面
Vue 教程:Vue Props
Vue 教程:Vue $emit() Method
Vue 教程:Vue Provide/Inject
Vue Reference: Vue $emit() Method
Vue 参考:Vue $root 对象