[Vuejs]-When one of the data attributes of Vue will change, Vue will re-execute all instruction operations

0👍

Because you embedded Math.random() in the template for the VUe, every time the DOM for the Vue needs to be updated (as in when you change msg), a new value will be calculated. One way you might solve this is to initialize the random value when the Vue is created.

var app = new Vue({
    el: "#app",
    data: {
        list: [{ name: "I am Tom" }, { name: "I am Mary" }],
        msg: "hello",
        random: Math.random()
    }
})

And then use the initialized value in your template.

<div id="app">
    <div v-for="item in list">
        <div> {{item.name}} </div>
        <div>{{random}}</div>
    </div>
    <div>{{random}}</div>
    <div>{{msg}}</div>
    <input type="text" v-model='msg'>
</div>

Another way you might solve the issue is to isolate the changes to msg in their own scope (a component).

Vue.component("message", {
  props:["msg"],
  template:`
    <div>
        <div>{{internalMessage}}</div>
        <input type="text" v-model='internalMessage'>
    </div>
  `,
  data(){
    return {
      internalMessage: this.msg
    }
  }
})
var app2 = new Vue({
  el: "#app2",
  data: {
    list: [{ name: "I am Tom" }, { name: "I am Mary" }],
    msg: "hello",
  }
})

And the template:

<div id="app2">
    <div v-for="item in list">
        <div> {{item.name}} </div>
        <div>{{Math.random()}}</div>
    </div>
    <div>{{Math.random()}}</div>
  <message :msg="msg"></message>
</div>

Here is an example of both approaches.

Leave a comment