一、单循环动态设置ref

1.设置:【:ref=“‘XXX’ + index”】XXX –>自定义ref的名字

2.获取:let 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": "这是来测试如何获取动态ref的"},{"id": 2,"title": "第2条数据"},{"id": 3,"title": "第3条数据"},{"id": 4,"title": "第4条数据"},]}},methods: {clickGetRef(index) {let ref = eval('this.$refs.refName' + index)[0]console.log(ref);}},}</script><style></style>

二、双循环动态设置ref

1.设置:【:ref=“‘XXX’ + (index+i)”】或者【:ref=“‘XXX’ + id”】
index+i –>两个for循环的索引;
id –>item的唯一标识;

2.获取:

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)"><div :ref="'refName1' + (index + i)">{{ item.title }}</div> ----<div :ref="'refName2' + sonItem.sonId">{{ sonItem.sonContent }}</div></div></div></div></div></template><script>export default {data() {return {dataLists: [{"id": 1,"title": "第1条数据","sonList": [{ "sonId": 1, "sonContent": "子集第1条数据" },{ "sonId": 2, "sonContent": "子集第2条数据" },]},{"id": 2,"title": "第2条数据","sonList": [{ "sonId": 11, "sonContent": "子集第11条数据" },{ "sonId": 22, "sonContent": "子集第22条数据" },]},{"id": 3,"title": "第3条数据","sonList": [{ "sonId": 111, "sonContent": "子集第111条数据" },{ "sonId": 222, "sonContent": "子集第222条数据" },]}]}},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>