zoukankan      html  css  js  c++  java
  • vue项目中,更改数组元素的值,视图没有实时更新?

    问题背景:

    export default {
      data(){
        showItems: [false, false, false, false]
      },
      methods: {
        showItem(index) {
          this.showItems[index] = true;
        },
        cancelItem(index) {
          this.showItems[index] = false;
        },
      },
    }
    

    如上代码,定义了showItems数组之后,通过点击按钮触发showItem和cancelItem函数来更改数组元素的值,发现页面上使用showItems数组元素的值并没有刷新,审查元素(如下图)找到该值,继续触发事件并查看发现元素值没有随着事件的触发而改变

    原因:

    由于 JavaScript 的限制及Vue实现响应式数据的原理,Vue 不能检测数组和对象的变化,具体原因参考Vue官网,我并没有对此深入理解。

    解决方法:

    我列出了四种(其中一种是评论者提供的)解决方法:

    1. this.$forceUpdate()

    用法:
    迫使 Vue 实例重新渲染。注意它仅仅影响实例本身和插入插槽内容的子组件,而不是所有子组件。参考Vue官网vm-forceUpdate

    export default {
      data(){
        showItems: [false, false, false, false]
      },
      methods: {
        showItem(index) {
          this.showItems[index] = true;
          this.$forceUpdate()
        },
        cancelItem(index) {
          this.showItems[index] = false;
          this.$forceUpdate()
        },
      },
    }
    
    1. this.$set(object, propertyName, value)

    用法:
    向响应式对象中添加一个 property,并确保这个新 property 同样是响应式的,且触发视图更新。它必须用于向响应式对象上添加新 property,因为 Vue 无法探测普通的新增 property,参考Vue官网Vue-set

    export default {
      data(){
        showItems: [false, false, false, false]
      },
      methods: {
        showItem(index) {
          this.$set(this.showItems, index, true)
        },
        cancelItem(index) {
          this.$set(this.showItems, index, false)
        },
      },
    }
    
    1. .push()

    用法:

    所以使用Vue包裹过的方法可以触发数据双向绑定

    export default {
      data(){
        showItems: [false, false, false, false]
      },
      methods: {
        showItem(index) {
         this.showItems[index] = true;
         this.showItems.push();
        },
        cancelItem(index) {
          this.showItems[index] = false;
          this.showItems.push();
        },
      },
    }
    
    1. .splice()

    此方法就是经过Vue包裹后的方法之一,还是下面可爱的评论者提供的,赞

    export default {
      data(){
        showItems: [false, false, false, false]
      },
      methods: {
        showItem(index) {
         this.splice(index, 1, true);
        },
        cancelItem(index) {
          this.splice(index, 1, false);
        },
      },
    }
    
    生活中不可能到处顺利,包括工作!
  • 相关阅读:
    学习笔记:模拟退火
    我的 2020
    高一上文化课期末复习
    IOI 2020-2021 集训队作业
    学习笔记:插头DP
    NOIP2020 游记
    刷题记录
    学习笔记:四边形不等式优化 DP
    操作集合时 报错 java.lang.UnsupportedOperationException
    【编码】接收前端参数时,偶数汉字正常,奇数汉字乱码
  • 原文地址:https://www.cnblogs.com/tizi/p/14600267.html
Copyright © 2011-2022 走看看