美文网首页
Vue使用$set动态给数据设置属性

Vue使用$set动态给数据设置属性

作者: leslie1943 | 来源:发表于2019-11-27 11:32 被阅读0次
    在实际的开发过程中,给表单元素绑定model的时候,绑定的元素的属性是根据后台数据动态生成的。如果使用常规的赋值方式,是无法更新视图的,需要使用, this.$set(dataName,keyName,keyValue)
    export default {
      data:{
        // 先定义一个空对象
        formObject:{}
      },
      mounted() {
        this.initPage()
      },
      methods:{
        initPage(){
          this.$store.dispatch(namespace/callData).then(res=>{
            // 给数据设置key-value
            res.data.forEach(item=>{
              // ❗❗❗❗❗ this.formObject[item.name] = item.value // ❗❗❗❗ 这种方式是不能更新视图的
              this.$set(this.formObject, item.name, item.value) // ✅✅✅✅可以更新视图
            })
          })
        }
      }
    }
    

    相关文章

      网友评论

          本文标题:Vue使用$set动态给数据设置属性

          本文链接:https://www.haomeiwen.com/subject/asqpwctx.html