Vue2.js dynamically adds responsive properties to objects

Hits: 0

Documentation:

The original document says

property must exist on the data object for Vue to convert it to reactive

However, I found a strange phenomenon, userInfo.agewhich is not datadefined in . When the button is clicked to update, the view in the view has userInfo.agealso changed.

<template>
  <div class="">
    <div class="userinfo">
      name: {{ userInfo.name }} age: {{ userInfo.age }}
    </div>

  </div>
</template>

<script>
export default {
  name: '',

  data() {
    return {
      userInfo: {
        name: 'Tom',
      },
    }
  },

  methods: {
    handleUpdateUserInfo() {
      this.userInfo.name = 'Jack'
      this.userInfo.age = 23
    },
  }
}
</script>

<style lang="less"></style>

<style lang="less" scoped></style>

However, if you update the agefields , the view doesn’t change

handleUpdateUserInfo() {
  // this.userInfo.name = 'Jack'
  this.userInfo.age = 23
},

So, userInfo.ageconsistent with what the documentation says, it’s not a responsive property, but userInfo.namean update that triggers a view update

Add a single reactive property

To make age also responsive and dynamically add responsive effects, you can use the this.$setmethod to dynamically set responsive properties

grammar

// Add responsive property to nested objects Vue.set 
( object , propertyName, value )

Example

handleUpdateUserInfo() {
  //   this.userInfo.name = 'Jack'
  //   this.userInfo.age = 23
  this.$set(this.userInfo, 'age', 23)
},

Add multiple reactive properties

handleUpdateUserInfo() {
   // create a new object 
  this .userInfo = { ... this .userInfo, age: 23 , school: 'pku' }
},

You may also like...

Leave a Reply

Your email address will not be published.