在 Vue 的 component 之間要如何存取彼此之間的資料,原生提供了幾種方法可以使用
- $root:存取 Vue 根物件的數據資料。
- $refs:存取自定義名稱的元件數據資料。
- $parent:存取父元件的數據資料。
- $children:存取直接子元件的數據資料。
$root
這個屬性用來存取目前 Vue 物件的根元件數據資料,如果目前的 Vue 物件中沒有父元件的話,則 $root 會等於自己,這個屬性只支援讀取。
//取得 Vue 根元件數據資料 console.log(this.$root.msg) //Vue 根物件 const APP = new Vue({ el: '#app', data: { msg: 'i'm msg' //根元件資料 } });
$refs
首先對組件使用 ref 屬性命名,就可以使用 $refs 來直接存取該元件。
<component-1 ref="c1">component-1</component-1> <component-2 ref="c2">component-2</component-2>
//使用 $ref 直接操作 this.$ref.c1 this.$ref.c2
$parent
想在子元件中存取父元件的屬性,可以使用 $parent 來直接操作。
//父元件 const APP = new Vue({ el: '#app', data: { msg: 'hello' } }); //取得父元件資料 this.$parent.msg
$children
在目前元件中可以使用 $children 來存取子元件的資料,取得的資料類型是 array,但取得的結果順序不一定,也不是響應式的,最好的方式是將取得的資料存放在當前的資料中再操作。
//取得子元件資料 let children = this.$children; //建立一個空 array 以存放 $children let childrenArray = []; //取得 $children 資料並排續存入 childrenArray for (let i = 0; i < children.length; i++){ childrenArray = childrenArray.push(children[i].msg); } //最後將新的 childrenArray 放入當前元件的資料中供使用 this.list = childrenArray;