gpt4 book ai didi

javascript - v-for 循环中的 Vue.js 引用

转载 作者:数据小太阳 更新时间:2023-10-29 05:20:48 26 4
gpt4 key购买 nike

我尝试在 v-for 循环中使用组件并初始化 ref 以便将来从父级访问其中的一些方法。这是我的案例的简化代码:

<template>
<div class="hello">
{{ msg }}
<ul>
<list-item
v-for="item in items"
:key="item.id"
:value="item.text"
:ref="`item${item.id}`"
/>
</ul>
</div>
</template>

<script>
import ListItem from "./ListItem";
export default {
name: "HelloWorld",
components: {
ListItem
},
data() {
return {
msg: "Welcome to Your Vue.js App",
items: [
{ id: 1, text: "foo" },
{ id: 2, text: "bar" },
{ id: 3, text: "baz" },
{ id: 4, text: "foobar" }
]
};
},
mounted() {
setTimeout(() => this.$refs.item2.highlight(), 1500);
}
};
</script>

ListItem组件:

<template>
<li v-bind:class="{ highlight: isHighlighted }">
{{value}}
</li>
</template>

<script>
export default {
name: "list-item",
props: ["value"],
data() {
return {
isHighlighted: false
};
},
methods: {
highlight() {
this.isHighlighted = !this.isHighlighted;
}
}
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.highlight {
color: red;
}
</style>

它只是呈现几个列表项并在一秒半后突出显示其中一个。但是我得到一个错误:Uncaught TypeError: _this.$refs.item2.highlight is not a function
在调试 session 之后,我发现了一个有趣的事实:在 v-for 循环中定义的引用不是组件,而是具有一个组件的数组。
逻辑是什么,f wrapper是什么?有人遇到这种情况吗?有人可以解释这种行为吗?
上面显示的代码与 setTimeout(() => this.$refs.item2[0].highlight(), 1500);
我必须始终传递 [0] 吗?有没有更好的方法?请帮忙。

最佳答案

在 v-for 中使用 refs 时,组件/DOM 节点作为数组直接存储到变量名称中,因此您无需在 ref 名称中使用索引号。所以你可以这样做:

<list-item
v-for="item in items"
:key="item.id"
:value="item.text"
ref="items"
/>

然后像这样在组件中使用 refs:

this.$refs.items[index]

另请注意,refs 可能没有按顺序排列,需要以不同的方式处理,这是一个完全不同的问题。您可以在此处关注:https://github.com/vuejs/vue/issues/4952

关于javascript - v-for 循环中的 Vue.js 引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52086128/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com