我是 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>
最佳答案
编辑 2
- 对于需要 react 性的所有对象更改,请使用
Vue.set(object, prop, value)
- 数组突变可以看目前支持的列表here
编辑 1
对于 vuex,您需要执行 Vue.set(state.object, key, value)
原创
因此,仅针对提出此问题的其他人。它出现在 Vue 2 的某个时刻。* 他们删除了 this.items.$set(index, val)
以支持 this.$set(this.items, index, val)
.
Splice 仍然可用,这里是 vue 中可用的数组变异方法的链接 link .
关于javascript - Vuejs 和 Vue.set(),更新数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42807888/