通过v-if指令强制刷新,当v-if的值发生变化时,组件都会被重新渲染一遍。因此,利用v-if指令的特性,可以达到强制刷新组件的目的。
先用个简单例子 --> 项目中使用
<template>
<comp v-if="refresh"></comp>
<button @click="refreshComp()">刷新comp组件</button>
</template>
<script>
import comp from '@/views/comp.vue'
export default {
name: 'parentComp',
data() {
return {
refresh: true
}
},
methods: {
refreshComp() {
// 移除组件
this.refresh = false
// 在组件移除后,重新渲染组件
// this.$nextTick可实现在DOM 状态更新后,执行传入的方法。
this.$nextTick(() => {
this.refresh = true
})
}
}
}
</script>
项目中使用
效果图:
<div v-if="isCheckComp == true">
<n-form-item
v-for="item in groups2"
:key="item.title"
:label="item.title"
>
<n-checkbox-group
v-model="item.checkedValues"
@update:value="handleCheckedChange2($event, item)"
>
<n-checkbox
v-for="option in item.options"
:key="option.value"
:value="option.value"
>{{ option.label }}</n-checkbox
>
</n-checkbox-group>
</n-form-item>
<n-button @click="clearAllSelections2">取消选中所有</n-button>
</div>
const groups2 = ref([
{
title: 'Group 1',
options: [
{ label: 'Option 1', value: 'option1' },
{ label: 'Option 2', value: 'option2' },
{ label: 'Option 3', value: 'option3' },
],
checkedValues: [],
},
{
title: 'Group 2',
options: [
{ label: 'Option A', value: 'optionA' },
{ label: 'Option B', value: 'optionB' },
{ label: 'Option C', value: 'optionC' },
],
checkedValues: [],
},
// 其他组...
]);
const handleCheckedChange2 = (event, item) => {
item.checkedValues = event;
};
const isCheckComp = ref(true);
const clearAllSelections2 = () => {
isCheckComp.value = false;
groups2.value.forEach((item) => {
//item.checkedValues = [] 不行,响应式不触发,使用下面的
item.checkedValues.splice(0, item.checkedValues.length);
});
// 强制刷新多选数据,确保数据回来渲染DOM
nextTick(() => {
isCheckComp.value = true;
});
};