参考
强制 Vue 组件重新渲染的方法(一) - 掘金 (juejin.cn)
强制 Vue 组件重新渲染的方法(二) - 掘金 (juejin.cn)
环境搭建
创建组件model_a,模拟要刷新的组件,每当重新加载时,都会在控制台输出提示
xml
<script setup>
import { onMounted } from 'vue'
onMounted(()=>{
console.log("加载组件")
})
</script>
<template>
<div>
this is a
</div>
</template>
<style scoped>
</style>
每当点击按钮时,都会去刷新组件
xml
<script setup>
import { ref,nextTick } from 'vue'
import model_a from "./model_a.vue"
</script>
<template>
<model_a></model_a>
<button style="border: 1px solid #ccc;" @click="refresh">
refresh
</button>
</template>
<style scoped>
</style>
演示
v-if
点击按钮后,flag的值会依次变为flase、true
重点是要等待dom操作结束后,再去更新flag状态由flase转化为true
多次点击后,也会对应的多次刷新组件页面
xml
<script setup>
import { ref,nextTick } from 'vue'
import model_a from "./model_a.vue"
let flag = ref(true)
async function refresh(){
flag.value = false
await nextTick()
flag.value = true
}
</script>
<template>
<model_a v-if="flag"></model_a>
<button style="border: 1px solid #ccc;" @click="refresh">
refresh
</button>
</template>
<style scoped>
</style>
key
每次点击按钮后,对应的key会依次加1,此时组件由于Key值变化会重新加载
xml
<script setup>
import { ref } from 'vue'
import model_a from "./model_a.vue"
const flag = ref(1)
async function refresh(){
flag.value += 1
console.log(flag.value)
}
</script>
<template>
<model_a :key="flag"></model_a>
<button style="border: 1px solid #ccc;" @click="refresh">
refresh
</button>
</template>
<style scoped>
</style>