[英]How to access an element's ref index within the nested v-for loop in vue.js?
是否可以使用元素的 refs 索引訪問嵌套 v-for 循環中的元素? 我的意思是,我試圖集中一個文本框,該文本框位於嵌套的 v-for 循環中,我曾經通過其 refs 索引訪問該循環。 它適用於單個 v-for 循環,但不適用於嵌套。
有關更多詳細信息,這是我的循環結構:
這有效
<div v-for="(comItem, index) in commentItems" :key="comItem.commentId">
<textarea ref="addRep" ></textarea>
</div>
this.$nextTick(() => {
this.$refs.addRep[index].focus()
});
這行不通
<div v-for="(cont, i) in contentItems" :key="cont.contentId">
...
<div v-for="(comItem, index) in commentItems" :key="comItem.commentId">
<textarea ref="addRep" ></textarea>
</div>
</div>
this.$nextTick(() => {
this.$refs.addRep[index].focus()
});
Or
this.$nextTick(() => {
this.$refs.addRep[i].focus()
});
具有嵌套的 html v-for 循環結構。 焦點會在任何地方跳躍。 對於遇到這種情況的任何人。 如果您知道解決方案,請幫助我。 謝謝。
嘗試在addRep
中計算適當的索引有點棘手。 您需要i
和index
的值,然后通過相關的 arrays 計算出適當的索引。
一種更簡單的方法是使用動態ref
名稱。 我們仍然需要i
和index
來找到相關元素,但不需要計算。
這里的核心技巧是將 ref 設置為:ref="`addRep${i}`"
,或者如果您願意,也可以等效地設置為:ref="'addRep' + i"
。 所以你最終會得到多個命名的 refs, addRep0
, addRep1
等,每個都有自己的元素數組。 i
的值告訴您參考名稱, index
告訴您該數組中的索引。
這是一個例子:
new Vue({ el: '#app', data () { return { contentItems: [ { contentId: 1, comments: [ { commentId: 1, text: 'A' }, { commentId: 2, text: 'B' }, { commentId: 3, text: 'C' } ] }, { contentId: 2, comments: [ { commentId: 1, text: 'D' } ] }, { contentId: 3, comments: [ { commentId: 1, text: 'E' }, { commentId: 2, text: 'F' } ] } ] } }, methods: { onButtonClick (i, index) { this.$refs[`addRep${i}`][index].focus() } } })
<script src="https://unpkg.com/vue@2.6.10/dist/vue.js"></script> <div id="app"> <div v-for="(cont, i) in contentItems":key="cont.contentId"> <h4>{{ cont.contentId }}</h4> <div v-for="(comItem, index) in cont.comments":key="comItem.commentId"> <textarea:ref="`addRep${i}`" v-model="comItem.text"></textarea> <button @click="onButtonClick(i, index)">Focus</button> </div> </div> </div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.