简体   繁体   English

Vue.js 道具复制和反应性

[英]Vue.js props copy and reactivity

Here's my problem: I have a v-for loop on a component.这是我的问题:我在组件上有一个 v-for 循环。 The v-for loop is based on an array filtered by a search term entered in an input and returned by a computed. v-for 循环基于由输入中输入的搜索词过滤并由计算返回的数组。

The child component displays some data based on a copy of past props because I need to modify them.子组件根据过去道具的副本显示一些数据,因为我需要修改它们。

The filtering works well but the content of the child components doesn't update correctly, being based on a copy of the props.过滤效果很好,但子组件的内容没有正确更新,基于道具的副本。

Here is a minimalist example: https://codesandbox.io/s/friendly-engelbart-8iu4u?file=/src/App.vue这是一个极简主义的例子: https://codesandbox.io/s/friendly-engelbart-8iu4u?file=/src/App.vue

You can see in the console that the filtering is good, but the visual result is not (try filtering for example with the letters "ba").您可以在控制台中看到过滤效果很好,但视觉结果却不是(尝试过滤,例如使用字母“ba”)。 How can I combine reactivity and props copy in a component?如何在组件中结合反应性和道具复制?

This caused by the :key isn't changing when you change the data since the :key value is based on the v-for index, not unique value that represent each user data.这是由:key导致的,因为:key值基于v-for索引,而不是代表每个用户数据的唯一值,所以在更改数据时不会更改。

Try adding id to the user object, and use it as the :key to make sure that each user data has its own unique :key尝试为用户 object 添加id ,并将其用作:key以确保每个用户数据都有自己唯一的:key

users: [
    {
        id: 1,
        lastname: "Einstein",
        firstname: "Albert"
    },
    ...
]

Demo: https://codesandbox.io/s/jolly-sun-optlr?file=/src/App.vue演示: https://codesandbox.io/s/jolly-sun-optlr?file=/src/App.vue

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM