在 vue 中 v-for 是用來循環(huán)的(component or dom). ref 則用來使用引用的(component or dom)
<li v-for="counter in 5" :key='counter'>{{counter}}</li>
<component v-for="counter in 5" :key='counter'></component>
<button ref="abc">normalButton</button>
<component :ref="propertyBindComponent"></component>
這沒什么大不了的.
v-for 循環(huán)唄,從后來取出來的 Array 數(shù)據(jù)肯定是需要用循環(huán)去遍歷顯示的. 不管它是一個(gè)復(fù)雜的組件還是單純的 li
ref 引用唄. 你引用的是dom, 那么我就可以通過 this.$refs.abc 來獲取這個(gè)按鈕,然后就像操作普通 dom 元素那樣該干嘛干嘛. 如果你引用的是一個(gè) 組件, 那么拿到的就是一個(gè)實(shí)例化好的 vue 組件對(duì)象. 里面的 methods, $data ... 該咋用咋用.
但是如果 v-for 和 ref 搭配在一起使用了呢???
單個(gè)vue-for 搭配 ref 使用
代碼:
// 魔板代碼
<ul>
<li v-for="(obj,index) in list1" :key="index" :ref="index">{{obj}}</li>
</ul>
data() {
return {
list1: ["a", "b", "c", "d"]
};
},
// 點(diǎn)擊按鈕進(jìn)行循環(huán)
hanlderClick () {
this.list1.forEach((obj,index,arr) => {
console.log(this.$refs[index][0].innerText
})
}
結(jié)果是:
a,b,c,d
乍看一看,覺得沒什么,就是這樣的.
仔細(xì)瞅瞅, this.$refs[index][0].innerText.
其中 index 是數(shù)組元素的索引,那么后面這個(gè) [0] 是干嘛使用的?????
多個(gè) v-for 搭配 ref
// 魔板代碼
<ul>
<li v-for="(obj,index) in list1" :key="index" :ref="index">{{obj}}</li>
</ul>
<ul>
<li v-for="(obj,index) in list2" :key="index" :ref="index">{{obj}}</li>
</ul>
data() {
return {
list1: ["a", "b", "c", "d"],
list2: [1, 2, 3, 4],
};
},
// 點(diǎn)擊按鈕進(jìn)行循環(huán)
hanlderClick () {
this.list1.forEach((obj,index,arr) => {
console.log(this.$refs[index][0].innerText
})
}
在一個(gè)組件的模板代碼中,有多個(gè) v-for , 我想循環(huán)第二個(gè)數(shù)組的 dom 元素呢???
代碼:
hanlderClick2 () {
this.list2.forEach((obj,index,arr) => {
console.log(this.$refs[index][1].innerText
})
}
看一下規(guī)律:
- 第一個(gè)數(shù)組的循環(huán)是
this.$refs[index][0].innerText - 第二個(gè)數(shù)組的循環(huán)是
this.$refs[index][1].innerText
區(qū)別在于第二個(gè)索引為 [0] & [1].
所以,結(jié)論就出來了.
在一個(gè)組件模板內(nèi)多個(gè) v-for 搭配 ref 的使用中,如果想獲取指定的 ref.
首先,你要確定兩個(gè)事件.
- 當(dāng)前元素在數(shù)組中的索引 .
[index] - 當(dāng)前元素在哪一個(gè)
v-for中循環(huán)的 ?[0]or[1].
最后總結(jié)
在同一個(gè)組件的模板中, 當(dāng)一個(gè)或者多個(gè) v-for 搭配 ref 時(shí).
想取出對(duì)應(yīng)的 ref 指向的(dom or component)..
語(yǔ)法規(guī)則是: this.$refs[當(dāng)前元素的索引][它是在第幾個(gè)v-for中循環(huán)的] .
this.$refs[先元素索引][在v-for索引]它和你理解是是一個(gè)反的.