我有一个名为"sortable"的自定义指令,但是我遇到了DOM问题.问题是当我拖放项目时,数组已更改,但DOM没有更改.
I have a custom directive called "sortable" but I ran into a problem with the DOM. The problem is when I dragged and dropped an item the array is changed but the DOM isn't.
这是我的自定义指令:
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".我有什么问题吗?
In my template I use: v-for="(task, index) in tasks". Did I something wrong?
推荐答案按照文档,以下方法将触发视图更新.包装的方法是:
As per the documentation, the following methods will trigger view updates. The wrapped methods are:
- push()
- pop()
- shift()
- unshift()
- splice()
- sort()
- reverse()
但是我看到您也在calculateCosts方法中执行此分配,由于腔室在Vue中:
However I see you are also doing this assignment in calculateCosts method, which will not trigger the mutation, due to caveats in vue:
this.tasks[index].costs = event.target.value * value;可以用以下内容替换它,以触发变异并借助 Object.assign 和 Vue.设置:
This can be replaced with the following to trigger the mutation and update the view with the help of Object.assign and Vue.set:
var newVal = Object.assign({}, this.tasks[index], {costs: event.target.value * value}) Vue.set(this.tasks, index, newVal)更多推荐
数组更改时VueJS dom不刷新
发布评论