The usage of this.$set in Vue can be used to modify an object in the array of objects and update data to the view

Keywords: Front-end Vue.js

The moon at night, thinking of those who miss

preface

Recently, I'm writing about the vue project arranged by the teacher. To tell the truth, I really jump across Baidu, google, bing and other search engines repeatedly every day. Otherwise, I'll search the Nuggets, think about it, and have a look at CSDN. My front-end grew up eating a hundred meals. I don't know how many problems I will encounter every day. Then basically, I asked all the front-end students around me. Basically, whoever is free will teach me.

There are too many detailed problems in the front end. Once there are problems that have not been touched, it will be very troublesome. If there are back-end partners learning from the front end, I think the fastest way to get familiar with the front end is to write the whole project. This is probably the fastest way to get started with the front-end frame.

1, Modify an object in the array under the array object in vue

My object structure is as follows:

sections: [
    {
        id: 0,
        addInputBool: true,
        generallnformationBool: false,
        generallnformation: '',
        updateGenerlInfoImgBool: false,
        pullUpQusetionBool: true,
        upQusetionBool: true,
        downQuestionBool: false,
        questions: [
           {
                id:'',
                   name:'',
                isCheckbox:'',
                answer:'',
                conditions:[],
                dropdownMultiSelections:[]
           }
       ]
    }
]

The requirement to be realized is to modify an object in the array through the array subscript.

At first, my idea was to assign values one by one into the array, just like writing Java code.

this.sections[index].question[id]=this.addQuestion

The index and id here are the values that we click on the page to modify. Finally, we find that there are always errors, so we can't modify them.

Later, Cha Baidu said:

Question:

Direct assignment according to the index of the array cannot modify the objects in the array.

reason:

Vue does not allow you to dynamically add new root level reactive properties on an already created instance. However, it can use the Vue.set(object, key, value) method to add response attributes to nested objects

Then it is found that this.$set should be used for operation

solve:

// Array: the first parameter is the array to be modified, the second value is the subscript or field to be modified, and the third is the value to be modified
this.$set(sections[index].question,id,{
    id:'123',
    name:'Ning Zaichun',
    isCheckbox:true,
    answer:'Test set',
    conditions:[1,2,3],
    dropdownMultiSelections:[a,b,c]
});
perhaps
// Object: the first parameter is the object to be modified, the second value is the property field to be modified, and the third is the value to be modified
Vue.set(sections[index].question,id,{     id:'123',
                                     name:'Ning Zaichun',
                                     isCheckbox:true,
                                     answer:'Test set',
                                     conditions:[1,2,3],
                                     dropdownMultiSelections:[a,b,c]})

When you see this.$set method, you want to know about it and see what application scenarios it has, so that you can use it directly next time you need it.

2, this.$set

2.1 what functions can this.$set achieve

Official explanation: add a property to the responsive object and ensure that the new property is also responsive and triggers view updates. It must be used to add new properties to a responsive object because Vue cannot detect common new properties (such as this.myObject.newProperty = 'hello, ningzai Chun')

Simply put, when you find that you have added a property to the object, which can be printed on the console, but it is not updated to the view, you may need to use this.$set () at this time

2.2. How to use this.$set

Vue in this.$set Usage of
// Array: the first parameter is the array to be modified, the second value is the subscript or field to be modified, and the third is the value to be modified
// Object: the first parameter is the object to be modified, the second value is the property field to be modified, and the third is the value to be modified
Vue.set( target, propertyName/index, value )

parameter
{Object | Array} target

{string | number} propertyName/index

{any} value

Small case:

<template>
  <div class="page" id="app">
    <button @click="add">set up</button>
    <ol>
      <li v-for="(item, index) in arr" :key="index">{{ item.name }}</li>
    </ol>
  </div>
</template>

<script>
export default {
  data () {
    return {
      arr: [
        { name: 'Ning Zaichun', age: 21 },
        { name: 'Northern Sangxia', age: 21 }
      ]
    }
  },
  mounted () {
    this.arr[2] = { name: 'Green winter chestnut', age: 23 } // The value of the array has changed, but the view has not changed
    console.log(this.arr)
  },
  methods: {
    add () {
      this.$set(this.arr, 2, { name: 'Green winter chestnut', age: 23 }) // $set triggers view change
    }
  }
}
</script>
target: Data source to change (can be an object or array)
key Specific data to change (index)
value Reassigned value

In vue's life cycle hook function mounted, we manually add a value to the array, but it will not be updated directly in the page view.

The initialized page is like this.

But on the console, it has actually been printed out

But if we click the button settings, the view will change immediately

This is a wonderful use of this.$set.

2.3. this.$set application scenario

1. In our use vue In the process of development, there may be a situation that when the vue instance has been generated, the data is assigned or added again, and the data cannot be updated synchronously.

2. In addition, I use this.$set to update data

think aloud

I feel shallow on paper. I absolutely know that I have to practice it.

Hello, I'm blogger Ning Zaichun: homepage

A young man who likes literature and art but embarks on the road of programming.

Hope: when we meet on another day, we have achieved something.

Posted by Usagi on Tue, 09 Nov 2021 09:45:13 -0800