【发布时间】:2019-02-04 18:07:41
【问题描述】:
我尝试在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
在调试会话之后,我发现了一个有趣的事实:在 v-for 循环中定义的引用不是组件,而是具有一个组件的数组。
什么是逻辑,什么是 f 包装器?有人遇到这种情况吗?有人可以解释这种行为吗?
上面显示的代码适用于setTimeout(() => this.$refs.item2[0].highlight(), 1500);
我必须总是通过[0] 吗?有没有更好的方法?请帮忙。
【问题讨论】:
-
When ref is used together with v-for, the ref you get will be an array containing the child components mirroring the data source.- 是吗?
标签: javascript vue.js vuejs2 vue-component