我有一个名为“sortable”的自定义指令,但我遇到了 DOM 问题。问题是当我拖放一个项目时,数组发生了变化,但 DOM 没有。
这是我的自定义指令:
Vue.directive('sortable', {
bind: function(el, binding, vnode) {
// Initialize sortable
this.sortable = Sortable.create(el, {});
console.debug("Sortable initialized");
this.sortable.option("onUpdate", function(event) {
binding.value.move(event.oldIndex, event.newIndex);
var updated = binding.value;
Vue.set(tasks, updated);
});
}
});
这就是我创建 Vue 实例的方式:
app = new Vue({
el: "#app",
data: {
subtotal: 0,
tasks: [
{name: '', quantity: '', rate: 80, costs: ''}
]
},
methods: {
newTask: function() {
this.tasks.push({name: '', quantity: '', rate: 80, costs: ''})
},
deleteTask: function(index) {
this.tasks.splice(index, 1);
this.calculateTotal();
},
calculateCosts: function(event, value, index) {
this.tasks[index].costs = event.target.value * value;
this.calculateTotal();
},
calculateTotal: function() {
this.subtotal = 0;
_.forEach(this.tasks, $.proxy(function(task) {
this.subtotal += task.costs;
}, this));
}
}
});
在我的模板中,我使用:v-for="(task, index) in tasks"
。我是不是做错了什么?
最佳答案
根据 documentation , 以下方法将触发 View 更新。包装的方法是:
- 推送()
- 弹出()
- 移位()
- 取消移位()
- 拼接()
- 排序()
- 反转()
但是我看到你也在 calculateCosts
方法中做这个分配,这不会触发突变,因为 caveats在 View 中:
this.tasks[index].costs = event.target.value * value;
这可以替换为以下内容以触发突变并在 Object.assign 的帮助下更新 View 和 Vue.set :
var newVal = Object.assign({}, this.tasks[index], {costs: event.target.value * value})
Vue.set(this.tasks, index, newVal)
关于javascript - 数组更改时 VueJS dom 不刷新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41267487/