SoFunction
Updated on 2025-04-05

VUE implements dynamically adding attributes to objects and triggering view update operation examples

This article describes the VUE implementation dynamically adding attributes to objects and triggering view update operations. Share it for your reference, as follows:

During the development process, we often encounter a situation where when a vue data declares or has been assigned objects or arrays (the value in the array is an object), a new attribute is added to the object. If the value of this attribute is updated, the view will not be updated.

According to the official documentation definition: If a new attribute is added to the instance after the instance is created, it will not trigger the view update.

Vue does not allow dynamic addition of new root-level responsive attributes on already created instances(root-level reactive property). However, it can use the (object, key, value) method to add response properties to nested objects.

We write the following code to test dynamically add attributes to an object:

<div >
  <input v-model="" /> 
  <input type="button" @click="demoSet()" value="setName">
</div>
<script type="text/javascript">
var vm=new Vue({
  el: "#app",
  data: {
    i:0,
    form:{}
  },
  methods:{
    demoSet(){
      =++;
      //this.$set(,"amount",++);
    }
  }
  });
</script>

This method can add a property to the form, but the interface will not respond to updates.

The correct way to do it:

<div >
  <input v-model="" /> 
  <input type="button" @click="demoSet()" value="setName">
</div>
<script type="text/javascript">
var vm=new Vue({
  el: "#app",
  data: {
    i:0,
    form:{}
  },
  methods:{
    demoSet(){
      this.$set(,"amount",++);
    }
  }
  });
</script>

This way you can add the amount attribute to the object.

What application scenarios do this have? For example, there are many attributes, most of which are not required. At this time, you can use this method to dynamically add required attributes.

It should be noted that this method cannot add attributes to the root data, such as:

<div >
  <input v-model="name" /> 
  <input type="button" @click="demoSet()" value="setName">
</div>
<script type="text/javascript">
var vm=new Vue({
  el: "#app",
  data: {
  },
  methods:{
    demoSet(){
      this.$set(this,"name","ray");
    }
  }
  });
</script>

This method adds a name attribute to data, which is invalid.

I hope this article will be helpful to everyone's programming.