Vue中的$set的使用

vue数据对象添加属性不更新问题

动态添加属性后,a属性并没有set和get函数,所以vue无法检测到数据的变化

使用vue设置属性,全局或者实例方法即可,此时视图会更新数据

        this.$set(this.stu, this.attr, this.value)
        Vue.set(this.stu, this.attr, this.value)

<template>
  <div>
    <p> {{stu}} </p>
    <input type="text" v-model="attr">
    <input type="text" v-model="value">
    <button @click="addAttr">add</button>
  </div>
</template>

<script>
  export default {
    name: "test",
    data() {
      return {
        stu: {
          name: 'ahao',
          age: 17
        },
        attr: '',
        value: '',
      }
    },
    methods: {
      addAttr() {
        this.stu[this.attr] = this.value
        console.log(this.stu)
      }
    }

  }
</script>

<style scoped>

</style>

猜你喜欢

转载自my.oschina.net/ahaoboy/blog/1788538