javascript - 数组更改时 VueJS dom 不刷新

标签 javascript laravel dom 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);
        });
    }
});

这就是我创建 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/

相关文章:

javascript - 未捕获的语法错误 : Unexpected token ILLEGAL on php json_encode

javascript - jQuery:如何查找动态生成 id 的单选按钮是否被选中?

javascript - Laravel 显示来自另一个数据库连接的图表

php - 如何使用 dom 解析器添加 php 标签

javascript - 如何创建用户输入(使用 javascript)

javascript - 如何从 Angular 工厂返回 bool 值

javascript - Ng 风格不起作用

Laravel 中间件 403

php - 如何在子域上上传 laravel 项目?

node.js - Node 中的 DOM 树到 HTML