本文介绍在 Vue 中实现组件销毁并重置的两种常用方法。第一种通过 watch 监听数据变化,利用 v-if 控制组件的销毁与重新渲染;第二种利用 :key 属性,通过递增 key 值强制 Vue 重建组件实例。
Vue 组件销毁并重置的两种实现方式
方法1
当数据发生变更时,可以通过 watch 监听器来触发组件的销毁与重新渲染。具体做法是利用 v-if 指令控制组件的显示状态,从而实现重置效果。
<template>
<third-comp v-if="reFresh"/>
</template>
<script>
export default{
data(){
return {
reFresh:true,
menuTree:[]
}
},
watch:{
menuTree(){
this.reFresh= false
this.$nextTick(()=>{
this.reFresh = true
})
}
}
}
</script>
方法2
<template>
<third-comp :key="menuKey"/>
</template>
<script>
export default{
data(){
return {
menuKey:1
}
},
watch:{
menuTree(){
++this.menuKey
}
}
}
</script>
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持本站。