数组更改时 VueJS dom 不刷新

VueJS dom doesn't refresh when array changed

我有一个名为 "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,以下方法将触发视图更新。包装的方法是:

  • 推()
  • 弹出()
  • 移位()
  • 取消移位()
  • 拼接()
  • 排序()
  • 反转()

但是我看到你也在 calculateCosts 方法中做这个赋值,这不会触发突变,因为 vue 中的 caveats:

this.tasks[index].costs = event.target.value * value;

这可以替换为以下内容以触发突变并在 Object.assign and Vue.set 的帮助下更新视图:

var newVal = Object.assign({}, this.tasks[index], {costs: event.target.value * value})
Vue.set(this.tasks, index, newVal)

要让 vue 接受它,请使用数组值中的正确唯一键,而不是数组索引:

<!-- use value.id in :key, not index -->
<div v-for="(value, index) in values" :key="value.id"> .... </div>