vue.js - 如何使用 ref 访问 v-for 循环内的元素

标签 vue.js vuejs2 vue-component v-for

尽可能简单地说:

我有一个 v-for 循环。我想访问循环迭代之一中的特定元素。由于某些原因,我只能使用 ref 来做到这一点。有办法做到这一点吗?

我尝试了各种不同的方法来实现这一点,但它总是返回未定义的。我的代码在 v-for 循环之外工作正常。

vue 的文档没有涵盖这个实例。

简化的循环:

  <div v-for="(item, i) in items">
    <div ref="card"></div>
  </div>

方法

 doThing() {
   card = elements.create('card');
   card.mount(this.$refs.card);
 }

最佳答案

由于不能保证数组引用按原始顺序排列,我发现在父级上注册一个引用更有帮助,然后使用常规 DOM API 来查找您想要的元素。

模板

<div ref="cards">
    <div v-for="(item, i) in items">
        <!-- this is a card -->
    </div>
</div>

JavaScript

{
    methods: {
        getCardAt(index) {
            return this.$refs.cards.children[index];
        }
    }
}

关于vue.js - 如何使用 ref 访问 v-for 循环内的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54084477/

相关文章:

javascript - Nuxt.js 中的开发工具样式编辑问题

Vue.js filterBy 多字段搜索

google-maps - 谷歌地图 : Cannot read property 'setDirections' of undefined

vuejs2 - Vue组件属性更改不会触发重新渲染

javascript - Vuejs中的: How to get an array index id?问题

javascript - Vue 2.5 动态下拉点击失败

javascript - Laravel-Vue 单元测试错误 "SyntaxError: Unexpected token {"

vue.js - 通过routerlink Vuejs传递对象

vue.js - 通过 Vue 中的数据属性传递函数引用

javascript - VueJS : how bind an checkbox with related select in simple Vue example?