数组更改时VueJS dom不刷新

编程入门 行业动态 更新时间:2024-10-27 10:20:15
本文介绍了数组更改时VueJS dom不刷新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个名为"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不刷新

本文发布于:2023-08-02 15:33:46,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1278931.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   VueJS   dom

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!