vue 中this.$set 动态绑定数据的案例讲解

感觉网上对this.$set的讲解乱糟糟的,我来总结一下对它单个数据、对象、数组、json数据的绑定.

话不多说直接上代码:

<template>
  <div>
    <!-- 单个数据 -->
    <button @click=\"text0a\">text0</button>
    <p>text0: {{text0}}</p>
    <!-- 对象 -->
    <button @click=\"textObja\">textObj</button>
    <p>textObj.text1: {{textObj.text1}}</p>
    <!-- 数组 -->
    <button @click=\"textArra\">textArr</button>
    <p>textArr[1]: {{textArr[1]}}</p>
    <!-- json数据 -->
    <button @click=\"textJsona\">textJson</button>
    <p>textJson[1].t5: {{textJson[1].t5}}</p>
  </div>
</template>
<script>
export default {
  data() {
    return{
      text0 : \'\',
      textObj: {},
      textArr: [],
      textJson:[
        {t0: \'\'},
        {t4: \'\'},
        {t7: \'\'},
      ]
    }
  },
  methods: {
    text0a: function () {
      let vm = this
      let text100 = \'efghjk\'
      vm.$set(vm,\'text0\',text100) 
      //等效于 vm.$set(vm,\'text0\',\'efghjk\')
    },
    textObja: function () {
      let vm = this
      let textObj100 = {
        text1: \'123\',
        text2: \'456\'
        }
      vm.$set(vm.textObj,\'text1\',textObj100.text1) 
      //此时等效于 vm.$set(vm,\'textObj\',textObj100)
    },
    textArra: function () {
      let vm = this
      let textArr200 = [\'a1\',\'a2\',\'a3\']
      vm.$set(vm,\'textArr\',textArr200)
    },
    textJsona: function () {
      let vm = this
      let textJson300 = [
        {t1: \'t1\',t2: \'t2\',t3: \'t3\'},
        {t4: \'t4\',t5: \'t5\',t6: \'t6\'},
        {t7: \'t7\',t8: \'t8\',t9: \'t9\'},
      ]
      vm.$set(vm.textJson[1],\'t5\',textJson300[1].t5) 
      //此时等效于 vm.$set(vm,\'textJson\',textJson300)
    }
  }
}
</script>
<style>
</style>

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

在实际的开发过程中,给表单元素绑定model的时候,绑定的元素的属性是根据后台数据动态生成的。如果使用常规的赋值方式,是无法更新视图的

需要使用

this.$set(dataName,keyName,keyValue)
export default {
 data:{
  // 先定义一个空对象
  formObject:{},
  arrayList:[],
 },
 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) // ✅✅✅✅可以更新视图
    })
   })
   // 修改数组
    this.$store.dispatch(namespace/callData).then(res=>{
    // 给数据设置key-value
    this.$set(this.arrayList,0,(res.data)[0].id) ✅✅✅✅可以更新视图
   })
  }
 }
}

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。如有错误或未考虑完全的地方,望不吝赐教。

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容