[Vuejs]-VueJS is updating another element on an event

4👍

Alireza already provided a workaround/solution but here comes the explaination.

When your Vue app loads it reads the template you have provided and replaces all the {{tags}} with the values. To get the value of {{getRandom()}} it calls the method getRandom().

Whenever any of the underlying values changes Vue will repeat this process. Now you see the new values on your screen. This is what they mean with Vue’s reactivity.

Now because you changed input_data the template gets reevaluated, which again calls the getRandom() function. This is why that value ‘unexpectedly’ changed when you inputted some text.

1👍

Edited:
vuejs use virtual DOM to re-rendering components when data changes, so when you use a method like that in your code, it runs getRandom() because of changing input_data.

you must put

getRandom(){
            return Math.random();
        },

in computed

computed:{
    getRandom(){
                return Math.random();
            },
},
methods: {

    setText(event){
        this.input_data = event.target.value;
    },
}

1👍

It happens because when you change component data (state), the component will be rerendered, And when component rerendered your getRandom() method will execute again and generate new random number.

In your case rerendering happens because you change the component data:

this.input_data = event.target.value;

If you want to prevent this behavior, you should put your getRandom() function in computed instead of methods.

Leave a comment