Vuejs 和 Vue.set(),更新数组

新手上路,请多包涵

我是 Vuejs 的新手。做了一些东西,但我不知道这是简单/正确的方法。

我想要的是

我想要数组中的一些日期并在事件中更新它们。首先我尝试了 Vue.set,但没有成功。现在更改我的数组项后:

 this.items[index] = val;
this.items.push();

我什么都没有推送到数组,它会更新..但有时最后一项会被隐藏,不知何故……我认为这个解决方案有点hacky,我怎样才能让它稳定?

简单的代码在这里:

 new Vue({
  el: '#app',
  data: {
  	f: 'DD-MM-YYYY',
    items: [
      "10-03-2017",
      "12-03-2017"
    ]
  },
  methods: {

    cha: function(index, item, what, count) {
    	console.log(item + " index > " + index);
      val = moment(this.items[index], this.f).add(count, what).format(this.f);
  		this.items[index] = val;
      this.items.push();
      console.log("arr length:  " + this.items.length);
    }
  }
})
 ul {
  list-style-type: none;
}
 <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.11/vue.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.6/moment.min.js"></script>
<div id="app">
  <ul>
    <li v-for="(index, item) in items">
    <br><br>
      <button v-on:click="cha(index, item, 'day', -1)">
      - day</button>
      {{ item }}
      <button v-on:click="cha(index, item, 'day', 1)">
      + day</button>
    <br><br>
    </li>
  </ul>
</div>

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

阅读 605
2 个回答

如果您像这样操作数组,VueJS 无法获取您对状态的更改。

正如 Common Beginner Gotchas 中所解释的,您应该使用诸如 push、splice 或其他方法之类的数组方法,并且永远不要像这样修改索引 a[2] = 2 也不要修改数组的 .length 属性。

 new Vue({
  el: '#app',
  data: {
    f: 'DD-MM-YYYY',
    items: [
      "10-03-2017",
      "12-03-2017"
    ]
  },
  methods: {

    cha: function(index, item, what, count) {
      console.log(item + " index > " + index);
      val = moment(this.items[index], this.f).add(count, what).format(this.f);

      this.items.$set(index, val)
      console.log("arr length:  " + this.items.length);
    }
  }
})
 ul {
  list-style-type: none;
}
 <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.11/vue.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.6/moment.min.js"></script>
<div id="app">
  <ul>
    <li v-for="(index, item) in items">
      <br><br>
      <button v-on:click="cha(index, item, 'day', -1)">
      - day</button> {{ item }}
      <button v-on:click="cha(index, item, 'day', 1)">
      + day</button>
      <br><br>
    </li>
  </ul>
</div>

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

编辑 2

  • 对于需要反应性的 所有 对象更改,请使用 Vue.set(object, prop, value)
  • 对于数组突变,您可以在 此处 查看当前支持的列表

编辑 1

对于 vuex,你会想要做 Vue.set(state.object, key, value)


原来的

因此,仅针对提出此问题的其他人。它出现在 Vue 2.* 他们删除了 this.items.$set(index, val) 支持 this.$set(this.items, index, val)

Splice 仍然可用,这里是 vue link 中可用的数组变异方法的链接。

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

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