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 物件