在 Vue2 中,我们可以使用动态绑定的方式来为 v-for 循环生成的元素动态绑定 ref。

首先,在 v-for 循环中使用 v-bind 指令将 ref 绑定到一个动态的属性上。例如,我们可以使用 `:ref=''item-' + index'` 来动态绑定 ref 属性,其中 index 是 v-for 循环中的索引。

接下来,在需要使用 ref 的地方,可以通过 `this.$refs` 来访问动态绑定的 ref。例如,可以使用 `this.$refs['item-' + index]` 来访问具有特定索引的元素的 ref。

下面是一个示例代码:

<template>
  <div>
    <div v-for="(item, index) in items" :ref=''item-' + index' :key="index">{{ item }}</div>
    <button @click="logRefs">Log Refs</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      items: ['item1', 'item2', 'item3']
    }
  },
  methods: {
    logRefs() {
      for (let index = 0; index < this.items.length; index++) {
        const ref = this.$refs['item-' + index];
        console.log(ref);
      }
    }
  }
}
</script>

在上面的示例中,我们使用 v-for 循环生成了一个包含三个元素的列表,并将每个元素的 ref 绑定到一个动态的属性上。当点击按钮时,会通过循环遍历访问每个元素的 ref,并打印到控制台上。

请注意,动态绑定 ref 的方式和动态绑定其他属性的方式是类似的,都是使用冒号(:)来进行动态绑定。


原文地址: https://www.cveoy.top/t/topic/qzbO 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录