阵列更改时,VueJS dom不会刷新

问题描述 投票:1回答:1

我有一个名为“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"。我有什么不对吗?

javascript laravel dom vuejs2
1个回答
13
投票

根据documentation,以下方法将触发视图更新。包装的方法是:

  • 推()
  • 流行()
  • 转移()
  • 不印字()
  • 拼接()
  • 分类()
  • 相反()

但是我看到你也在calculateCosts方法中做这个任务,由于qaz中的caveats,它不会触发变异:

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

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

var newVal = Object.assign({}, this.tasks[index], {costs: event.target.value * value})
Vue.set(this.tasks, index, newVal)
© www.soinside.com 2019 - 2024. All rights reserved.