v-for 循环中的 Vue.js ref

新手上路,请多包涵

我尝试在 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] 吗?有没有更好的方法?请帮忙。

原文由 Lev Khruschev 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 506
1 个回答

当使用带有 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]

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

原文由 Sagar Chakravarthy 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题