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

jus*_*g96 1 javascript dom laravel vuejs2

我有一个名为"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);
        });
    }
});
Run Code Online (Sandbox Code Playgroud)

这就是我创建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));
        }
    }
});
Run Code Online (Sandbox Code Playgroud)

在我的模板中,我使用:v-for="(task, index) in tasks".我有什么不对吗?

Sau*_*abh 14

文档相同,以下方法将触发视图更新.包装的方法是:

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

但是我发现你也在做calculateCosts方法中的跟随,由于vue中的警告,它不会触发变异:

this.tasks[index].costs = event.target.value * value;
Run Code Online (Sandbox Code Playgroud)

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

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

  • 谢谢你的反应.我在Laravel论坛上提出了同样的问题,现在已修复.唯一的问题是我忘记了:key = DOM内的任务.但不管怎样,谢谢. (2认同)