Vue使用Ref跨層級獲取組件實例
Vue使用Ref跨層級獲取組件實例
示例介紹
在開發過程中,我們難免會使用到跨層級的ref實例獲取,大部分情況下,我們都可以通過組件自身的parent
或者children
去找到需要的實例。但是當層級不明顯或者太深的時候,用此方法難免過於臃腫和低效率。
如下圖所示,我們通過組件E
去獲取組件D
的組件實例。
文檔目錄結構
分別有A、B、C、D、E和index六個組件,並按照上圖的組件順序,分別插入到各自的頁面中。
頁面樣式如下:
安裝vue-ref
- 下載vue-ref
npm install vue-ref –save
- 全局註冊
import ref from 'vue-ref' Vue.use(ref)
- 使用方法
<!-- vm.dom will be the DOM node -->
<p v-ref="c => this.dom = c">hello</p>
<!-- vm.child will be the child component instance -->
<child-component v-ref="c => this.child = c"></child-component>
<span v-for="n in 10" :key="n" v-ref="(c, key) => {...}">{{ n }} </span>
根組件自定義方法[使用provide和inject]
我們index頁面中,提供了三個方法:分別用來:
- 設置子組件的實例,setChildrenRef
- 獲取自組件實例, getChildrenRef
- 獲取當前節點實例, getRef
provide() {
return {
setChildrenRef: (name, ref) => {
this[name] = ref
},
getChildrenRef: name => {
return this[name]
},
getRef: () => {
return this
}
}
},
分別說明各個頁面
組件A頁面:
通過注入的方法,獲取setChildrenRef方法,並通過上述指令,將組件D快取起來
組件B頁面:
組件C頁面:
組件D頁面:
組件E頁面:
在這個頁面中,我們不僅注入了兩個方法,還設置了切換D組件顏色的方法,用來測試我們是否真的跨層級獲取到了組件D的實例。
結果
可以看到,三個parent的實例是一樣的,在組件E中也成功修改了組件D的文字樣式。good!