It is pointed out in the official documentation of Vue that it has the effect of forcing refresh.
That in the vue framework, if there is a variable: age, modify it, the page will be updated automatically.
However, if the variable in it is an array or object, we go directly to an object or array to add properties, and the page is not recognized$forceUpdate
Vue.$forceUpdate(): Forces the Vue instance to re-render, note that it only affects the instance itself and the child components that insert the slot content, not all child components.
<template>
<p>{{userInfo.name}}</p>
<button @click="updateName">edit userInfo</button>
</template>
<script>
data(){
return{
userInfo: {name:'Jack'}
}
},
methods:{
updateName(){
this.userInfo.name='Tom'
}
}
</script>
in the function, we try to modify the value of the object and find that the page has not actually changedupdateNameuserInfo
at this time, there are two solutions:
method 1:
methods:{
updateName(){
this.userInfo.name='Tom' // At this point, the userInfo object has indeed been modified
console.log(this.userInfo.name); // Output: Tom
this.$forceUpdate(); // Here, after a forced refresh, the result of the page becomes Tom
}
}
method 2:
methods:{
updateName(){
this.$set('userInfo',name,'Tom');
}
}
fantastic ? dynamic rendering of elements bound to data, change the value of data, the page did not refresh, with this forced update directly solved! club!