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.
- [Vuejs]-How to destroy Swiper slider for VueJS
- [Vuejs]-Vue-router routes to the wrong page, the link has to add a '#' before the path
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;
},
}
- [Vuejs]-Nest an inline template inside of a .vue component
- [Vuejs]-How use Regex in Localization Laravel 5.4 with Vue JS
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.
- [Vuejs]-Accessing Vue.$router inside an external "service" class
- [Vuejs]-VueJS – Update Parent Data After Ajax