Vue使用Ref跨層級獲取組件的步驟
在開發過程中,我們難免會使用到跨層級的ref實例獲取,大部分情況下,我們都可以通過組件自身的parent或者children去找到需要的實例。但是當層級不明顯或者太深的時候,用此方法難免過于臃腫和低效率。
如下圖所示,我們通過組件E去獲取組件D的組件實例。
分別有A、B、C、D、E和index六個組件,并按照上圖的組件順序,分別插入到各自的頁面中。
頁面樣式如下:
下載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 獲取當前節點實例, getRefprovide() { 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!
以上就是Vue使用Ref跨層級獲取組件的步驟的詳細內容,更多關于vue 使用Ref獲取組件的資料請關注好吧啦網其它相關文章!
相關文章: