This is the fourth day of my participation in the November Gwen Challenge. Check out the details: The last Gwen Challenge 2021
The problem
I recently encountered a requirement to re-render the current component. This is easy to do, just tell the parent to rerender.
Here I summarize the ways I know how vUE components can be rerendered.
Change the key
This is the most recommended.
Because VUE judges the change of elements through virtual Dom algorithm, the core of whether the elements change is to determine whether the key value of the old and new elements changes. If your key is changed, re-render the element, if the key is unchanged, it is not re-rendered.
So if you want to re-render your component, you add the key property to the component, and then when you need to re-render, you change the key value.
Components are re-rendered, and the corresponding lifecycle functions, computed properties, watch, and so on are executed.
<template>
<div class="home">
<el-button @click="freshKey">test</el-button>
<aComp :key="key"></aComp>
</div>
</template>
<script>
import aComp from '@/components/aComp'
export default {
components: {
aComp
},
data () {
return {
key: 0}},methods: {
freshKey () {
this.key++
}
}
}
</script>
Copy the code
v-if
V-if is also more common among the instructions we use.
When set to false, elements contained in the current condition block are destroyed, and if contained components, the component’s lifecycle functions (beforeDestroy, destroyed, etc.) are executed.
When set to True, the element in the conditional block will be reconstructed. If it contains a component, the component’s lifecycle functions (created, Mounted, etc.), calculation properties, watch, etc., will be executed, which is equivalent to re-rendering.
vm.$forceUpdate()
This method is not used much, but forces the view to be updated.
But vUE is bidirectional binding, data changes, and views refresh in real time. When is this used?
For example, vue’s array-only methods refresh the view:
push()
pop()
shift()
unshift()
splice()
sort()
reverse()
So when you reassign a value to an array, for example, vue does not refresh the view. Then you can use this method to force the view to refresh.
export default {
data () {
return {
arr: [1.2.3]}},methods: {
editArr () {
this.arr[0] = 0 // The view will not refresh
},
forceUpdate () {
this.$forceUpdate() Calling this method refreshes the view}}}Copy the code
When a vue instance executes this method, it only refreshes the view, and the instance’s corresponding lifecycle functions, calculation properties, watch, etc., are not re-executed.