vue如何在for循環(huán)中設置ref并獲取$refs
一、單循環(huán)動態(tài)設置ref
1.設置:【:ref=“‘XXX’ + index”】XXX -->自定義ref的名字
2.獲?。簂et ref = eval(‘this.$refs.XXX’ + index)[0]
3.示例:
代碼如下所示
<template> <div class="ref_test"> <div v-for="(item, index) in dataList" :key="index" :ref="'refName' + index" @click="clickGetRef(index)"> <p>{{ item.title }}</p> </div> </div> </template> <script> export default { data() { return { dataList: [ { "id": 1, "title": "這是來測試如何獲取動態(tài)ref的" }, { "id": 2, "title": "第2條數(shù)據(jù)" }, { "id": 3, "title": "第3條數(shù)據(jù)" }, { "id": 4, "title": "第4條數(shù)據(jù)" }, ] } }, methods: { clickGetRef(index) { let ref = eval('this.$refs.refName' + index)[0] console.log(ref); } }, } </script> <style></style>
二、雙循環(huán)動態(tài)設置ref
1.設置:【:ref=“‘XXX’ + (index+i)”】或者【:ref=“‘XXX’ + id”】
index+i -->兩個for循環(huán)的索引;
id -->item的唯一標識;
2.獲?。?/p>
let ref = eval('this.$refs.XXX' + (index + i))[0] 或者 let ref = eval('this.$refs.XXX' + (item.id))[0]
3.示例:
代碼如下所示
<template> <div> <div class="ref_double_test"> <div v-for="(item, index) in dataLists" :key="index"> <div class="content" v-for="(sonItem, i) in item.sonList" :key="index + i" @click="clickGetDoubleRef(index, i, sonItem)"> <!-- 方式一:用索引的方式,用一個索引可能會重復,為防止重復,則用兩個索引【index + i】 --> <div :ref="'refName1' + (index + i)">{{ item.title }}</div> ---- <!-- 方式二:用id的方式 --> <div :ref="'refName2' + sonItem.sonId">{{ sonItem.sonContent }}</div> </div> </div> </div> </div> </template> <script> export default { data() { return { dataLists: [ { "id": 1, "title": "第1條數(shù)據(jù)", "sonList": [ { "sonId": 1, "sonContent": "子集第1條數(shù)據(jù)" }, { "sonId": 2, "sonContent": "子集第2條數(shù)據(jù)" }, ] }, { "id": 2, "title": "第2條數(shù)據(jù)", "sonList": [ { "sonId": 11, "sonContent": "子集第11條數(shù)據(jù)" }, { "sonId": 22, "sonContent": "子集第22條數(shù)據(jù)" }, ] }, { "id": 3, "title": "第3條數(shù)據(jù)", "sonList": [ { "sonId": 111, "sonContent": "子集第111條數(shù)據(jù)" }, { "sonId": 222, "sonContent": "子集第222條數(shù)據(jù)" }, ] } ] } }, methods: { clickGetDoubleRef(index, i, sonItem) { // 方式一 let ref1 = eval('this.$refs.refName1' + (index + i))[0] console.log('ref1', ref1); // 方式二 let ref2 = eval('this.$refs.refName2' + sonItem.sonId)[0] console.log('ref2', ref2); } }, } </script> <style> .ref_test { width: 500px; height: 100px; border: 1px solid gray; } .content { width: 500px; height: 30px; display: flex; background: rebeccapurple; margin-bottom: 10px; } </style>
總結
到此這篇關于vue如何在for循環(huán)中設置ref并獲取$refs的文章就介紹到這了,更多相關vue循環(huán)設置ref并獲取$refs內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Vue?element-ui?el-cascader?只能末級多選問題
這篇文章主要介紹了Vue?element-ui?el-cascader?只能末級多選問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-09-09