我是 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 许可协议
如果您像这样操作数组,VueJS 无法获取您对状态的更改。
正如 Common Beginner Gotchas 中所解释的,您应该使用诸如 push、splice 或其他方法之类的数组方法,并且永远不要像这样修改索引
a[2] = 2
也不要修改数组的 .length 属性。