javascript - Vue,数据和计算之间的组件值不同?

标签 javascript vue.js vue-component

我在代码中发现组件数据中显示的值不是我想要的值。代码如下:

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/

相关文章:

vue.js - 如何设置全局导入的Vue组件具有预设属性?

javascript - jQuery 使用 IFRAME 内容中的 RegEx

javascript - 使用 addEventListener 识别 chrome 扩展中元素的 id

javascript - 为什么 Polymer 不读取行为属性?

vue.js - 用户使用 token 身份验证登录后如何隐藏登录路由导航元素?

vue.js - 父子vue之间的异步生命周期

javascript - 我在绘图程序中的 undoTheUndo 无法在圆上执行,但在直线上执行

vue.js - Vue中如何加载外部CSS

javascript - 通过标签过滤数组 Vuejs

vue.js - 在 Vue.js 2.6 中使用 Javascript 访问 <slots> 的内容