Use of this.$set in vue

This is the 16th day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021

Background: When I wrote the front end project, the back end gave us a JSON object that I had rendered on the page. However, due to my own needs, I want to add a field to the returned object, so I use push to add a field, add is added, but the page rendering does not change. Then I realized it wasn’t responsive. If we want the new field to be responsive, we use this.$set to inject data

When an object or array is declared or assigned to vue’s data, a new property is added to the object. If the value of the property is updated, the view is not updated.

use

This.$set(target, key, value) Target: data source, array or object you want to manipulate, key: field to manipulate, value: changed data

Here’s a quick example:

Add an age attribute to an object and let it change in response

<template> <div class="text"> <p>{{list}}</p> <button @click="add">age++</button> </div> </template> <script> export Default {data(){return {list:{name: "zhang Three "}}}, methods: {add(){if(! Age =18}else{this.list.age++} console.log(this.list)}}} </script>Copy the code

When we do not use this.$set to add an object attribute, the effect is:

The data has indeed been added, but the page does not have a responsive render age attribute.

$set(this.list,’age’,18) to add an attribute. Effect:

We can see that the added data is reactive.

Why is it reactive?

$set = getAge; $set = getAge; $set = getAge

Analysis of the

The responsivity principle of Vue is that a JavaScript object passes a Vue instance as the data option, and Vue iterates through all of the object’s properties, And use Object.defineProperty to turn all of these properties into getters/setters. These getters/setters are invisible to the user, but internally they allow Vue to track dependencies and notify changes when the property is accessed and modified. Note here that different browsers format getters/setters differently when printing data objects on the console, as shown in the following figure from the official documentation.

Write in the last

If above is wrong, welcome big guy comment to give directions.

Romantic statement of the Day

💌 Crabs are peeling my shell and notebooks are writing about me.

All over the sky I fall on the maple leaf snowflakes.

And you’re thinking about me. — “Three Quotation Book of Wuhan University”