Nat*_*iel 2 vue.js vue-component vuejs2 v-for
尽可能简单地说:
我有一个 v-for 循环。我想访问循环迭代之一中的特定元素。出于某些原因,我只能使用 ref 来做到这一点。有没有办法做到这一点?
我尝试了各种不同的方法来实现这一点,但它总是返回未定义。我的代码在 v-for 循环之外运行良好。
vue 的文档没有涵盖这个实例。
循环简化:
<div v-for="(item, i) in items">
<div ref="card"></div>
</div>
Run Code Online (Sandbox Code Playgroud)
方法
doThing() {
card = elements.create('card');
card.mount(this.$refs.card);
}
Run Code Online (Sandbox Code Playgroud)
任何帮助将非常感激。
由于不能保证数组引用按原始顺序排列,我发现在父级上注册一个引用更有帮助,然后使用常规 DOM API 查找您想要的元素。
<div ref="cards">
<div v-for="(item, i) in items">
<!-- this is a card -->
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
{
methods: {
getCardAt(index) {
return this.$refs.cards.children[index];
}
}
}
Run Code Online (Sandbox Code Playgroud)