Vue.js - 更新后的数组项值未在页面中更新
Vue.js - updated array item value doesn't update in page
"test"是我的vue数据中的对象数组
var vue = new Vue({
el: '#content',
data: {
test: [
{
array: [0, 0, 0, 0]
},
{
array: [0, 0, 0, 0]
}
],
number: 0
},
methods: {
setNumber: function(){
this.number = 5;
},
setArray: function(){
this.test[0].array[0] = 9;
}
}
})
问题是,如果我更改 "array" 中某个元素的值,而日志显示该值已更改,它不会在页面上更新。另一方面,如果我更改 "number" 的值,则页面上的 "number" 和 "array" 值都会更新。
<section id="content">
<div>Value in array: {{ test[0].array[0] }}</div>
<div>Value in number: {{ number }}</div>
<!-- {{ setNumber() }} -->
{{ setArray() }}
</section>
<!-- Loading Vue.js -->
<script src="https://unpkg.com/vue"></script>
<script src="https://cdn.jsdelivr.net/vue.resource/1.3.1/vue-resource.min.js"></script>
如何让我的页面响应 "array" 更新?
这是 JsFiddle:https://jsfiddle.net/zcbh4esr/
这是由于array change caveats。
改为这样做
var vue = new Vue({
el: '#content',
data: {
test: [{
array: [0, 0, 0, 0]
}, {
array: [0, 0, 0, 0]
}],
number: 0
},
methods: {
setNumber: function() {
this.number = 5;
console.log(this.number);
},
setArray: function() {
//this.test[0].array[0] = 9;
this.$set(this.test[0].array, 0, 9);
console.log(this.test[0].array[0]);
}
}
});
这里是fiddle
不要更新数组中的项目,试试这个
this.users = Object.assign({},newList);
这将更新 DOM。
来自
https://vuejs.org/v2/guide/reactivity.html
var vm = new Vue({
data: {
items: ['a', 'b', 'c']
}
})
//vm.items[1] = 'x' // is NOT reactive
Vue.set(vm.items, indexOfItem, newValue) //works fine
对我有用
"test"是我的vue数据中的对象数组
var vue = new Vue({
el: '#content',
data: {
test: [
{
array: [0, 0, 0, 0]
},
{
array: [0, 0, 0, 0]
}
],
number: 0
},
methods: {
setNumber: function(){
this.number = 5;
},
setArray: function(){
this.test[0].array[0] = 9;
}
}
})
问题是,如果我更改 "array" 中某个元素的值,而日志显示该值已更改,它不会在页面上更新。另一方面,如果我更改 "number" 的值,则页面上的 "number" 和 "array" 值都会更新。
<section id="content">
<div>Value in array: {{ test[0].array[0] }}</div>
<div>Value in number: {{ number }}</div>
<!-- {{ setNumber() }} -->
{{ setArray() }}
</section>
<!-- Loading Vue.js -->
<script src="https://unpkg.com/vue"></script>
<script src="https://cdn.jsdelivr.net/vue.resource/1.3.1/vue-resource.min.js"></script>
如何让我的页面响应 "array" 更新?
这是 JsFiddle:https://jsfiddle.net/zcbh4esr/
这是由于array change caveats。
改为这样做
var vue = new Vue({
el: '#content',
data: {
test: [{
array: [0, 0, 0, 0]
}, {
array: [0, 0, 0, 0]
}],
number: 0
},
methods: {
setNumber: function() {
this.number = 5;
console.log(this.number);
},
setArray: function() {
//this.test[0].array[0] = 9;
this.$set(this.test[0].array, 0, 9);
console.log(this.test[0].array[0]);
}
}
});
这里是fiddle
不要更新数组中的项目,试试这个
this.users = Object.assign({},newList);
这将更新 DOM。
来自
https://vuejs.org/v2/guide/reactivity.html
var vm = new Vue({
data: {
items: ['a', 'b', 'c']
}
})
//vm.items[1] = 'x' // is NOT reactive
Vue.set(vm.items, indexOfItem, newValue) //works fine
对我有用