What happens when adding a new property to the object property in data in Vue? How to solve?

    • What happens when adding a new property to the object property in data in Vue? How to solve?

<template>
 <div>
 <ul>
 <li v-for="value in obj" :key="value"> {
    
    {value}} </li>
 </ul>
 <button @click="addObjB">添加 obj.b</button>
 </div>
</template>
<script>
 export default {
 data () {
 return {
 obj: {
 a: 'obj.a'
 }
 }
 },
 methods: {
 addObjB () {
 this.obj.b = 'obj.b'
 console.log(this.obj)
 }
 }
 }
</script>

Click the button and you will find that obj.b has been successfully added, but the view is not refreshed. This is because when the Vue instance is created, obj.b is not declared, so it is not converted into a responsive property by Vue, and naturally it will not trigger the update of the view. At this time, you need to use Vue's global api $set() :

addObjB () (
 this.$set(this.obj, 'b', 'obj.b')
 console.log(this.obj)
}

The $set() method is equivalent to manually processing obj.b into a responsive property, and the view will also change accordingly.

Guess you like

Origin blog.csdn.net/weixin_71171795/article/details/128550922