我在代码中发现组件数据中显示的值不是我想要的值。代码如下:
View.component('xxx-item',{
props:['item'],
template:`xxxx`,
computed:{
computedTest(){
return this.item.id
}
},
data:function(){
return{
test:this.item.id
}
}
}
xxx-item 用于列表中的项目,如下所示:
<xxx-list v-for="item in xxxList" v-bind:item="item"></xxx-list>
我认为 this.test 和 this.compulatedTest 的值,这意味着 this.item.id 应该相同。但有时它们实际上是不同的。为什么?数据中的值和计算值之间有什么区别?
项目数据设置如下:
function loading(){
axiox.get(xxx)
.then((res)=>{
let result = [];
for(let item of res.xxx.list){
let obj = {};
obj.id = item.id;
.............
.............
result.push(obj);
}
this.xxxList = result;
})
}
最佳答案
Vue 将在重新渲染期间尽可能重用组件。这意味着如果您添加、删除或重新排序 xxxList
中的项目,然后是一些<xxx-item>
组件将绑定(bind)到不同的项目。计算属性computedTest
将更新以反射(reflect)此更改,但数据属性 test
不会改变,因为它只在组件实例化时设置一次。
您需要使用 key
上<xxx-item>
以确保相同的组件实例用于数组中的相同项目。
例如
<xxx-item v-for="item in xxxList" :key="item.id" :item="item">
When Vue is updating a list of elements rendered with
v-for
, by default it uses an "in-place patch" strategy. If the order of the data items has changed, instead of moving the DOM elements to match the order of the items, Vue will patch each element in-place and make sure it reflects what should be rendered at that particular index.
关于javascript - Vue,数据和计算之间的组件值不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50961838/