Case Study of this. $set Dynamic Binding Data in vue

  • 2021-10-25 05:52:59
  • OfStack

Feeling that the online explanation of this. $set is messy, let me summarize the binding of its single data, objects, arrays and json data.

Don't say much and go directly to the code:


<template>
  <div>
    <!--  Single data  -->
    <button @click="text0a">text0</button>
    <p>text0: {{text0}}</p>
    <!--  Object  -->
    <button @click="textObja">textObj</button>
    <p>textObj.text1: {{textObj.text1}}</p>
    <!--  Array  -->
    <button @click="textArra">textArr</button>
    <p>textArr[1]: {{textArr[1]}}</p>
    <!-- json Data  -->
    <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) 
      // Equivalent to  vm.$set(vm,'text0','efghjk')
    },
    textObja: function () {
      let vm = this
      let textObj100 = {
        text1: '123',
        text2: '456'
        }
      vm.$set(vm.textObj,'text1',textObj100.text1) 
      // At this time, it is equivalent to  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) 
      // At this time, it is equivalent to  vm.$set(vm,'textJson',textJson300)
    }
  }
}
</script>
<style>
</style>

Add: Vue uses $set to dynamically set properties for data

In the actual development process, when binding model to form elements, the attributes of the bound elements are dynamically generated according to the background data. You cannot update the view if you use the normal assignment method

Need to use


this.$set(dataName,keyName,keyValue)

export default {
 data:{
  //  Define first 1 Empty object 
  formObject:{},
  arrayList:[],
 },
 mounted() {
  this.initPage()
 },
 methods:{
  initPage(){
   this.$store.dispatch(namespace/callData).then(res=>{
    //  Set the data key-value
    res.data.forEach(item=>{
     // ❗❗❗❗❗ this.formObject[item.name] = item.value // ❗❗❗❗  You cannot update the view in this way 
     this.$set(this.formObject, item.name, item.value) // ✅✅✅✅ You can update the view 
    })
   })
   //  Modify Array 
    this.$store.dispatch(namespace/callData).then(res=>{
    //  Set the data key-value
    this.$set(this.arrayList,0,(res.data)[0].id) ✅✅✅✅ You can update the view 
   })
  }
 }
}

Related articles: