zoukankan      html  css  js  c++  java
  • 为data中的某一个对象添加一个属性不起作用——this.$set的正确使用

    this.$set(obj, key, value)

    我们在项目开发的过程中,经常会遇到这种情况:为data中的某一个对象添加一个属性

    <template>
      <div class="hello">
        <button @click="setMessage">添加属性</button>
        {{ student.name }}
        <input type="text" v-model="student.age">
      </div>
    </template>
    
    
    <script>
    export default {
      data() {
        return {
          student: {
            name: '张三',
          }
        }
      },
      methods: {
        setMessage() {
          this.student.age = 15
          console.log(this.student)
        }
      }
    }
    </script>
    
    

    虽然这个对象身上已经有了该属性,但是视图层并没有更新该数据,是什么造成的呢?由于受JavaScript的限制,vue.js不能监听对象属性的添加和删除,因为在vue组件初始化的过程中,会调用getter和setter方法,所以该属性必须是存在在data中,视图层才会响应该数据的变化
    那么,我们该如何解决这个问题呢
    解决这个问题的方法:

    使用this.$set(obj, key, value)/vue.set(obj, key, value)

    <script>
    export default {
     data() {
       return {
         student: {
           name: '张三',
         }
       }
     },
     methods: {
       setMessage() {
         this.$set(this.student, 'age', 15)
         console.log(this.student)
       }
     }
    }
    </script>
    
    
  • 相关阅读:
    顺序查找
    折半查找
    KMP
    php长时间的脚本,报502
    AcWing 27. 数值的整数次方
    acwing 25. 剪绳子
    Best Cow Line <挑战程序设计竞赛> 习题 poj 3617
    acwing 23. 矩阵中的路径
    AcWing 34. 链表中环的入口结点
    AcWing 33. 链表中倒数第k个节点
  • 原文地址:https://www.cnblogs.com/maizilili/p/12298036.html
Copyright © 2011-2022 走看看