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