在Vue中如何对组件进行销毁在进行挂载
今天有个需求,每次进入这个组件的时候都会运行mounted方法,比如有个组件A,组件A里有一个按钮,每点击这个按钮,组件B就会运行这个mouted方法,这时候我们想到的就是让这个组件先变为null 在重新给他赋值
<template><div><h1>{{ msg }}</h1><button @click="changeComp">切换组件</button><component :is="comp" /></div></template><script>
import TheWelcome from './components/TheWelcome.vue'export default {name: 'App',components: {thewelcome:TheWelcome},data() {return {msg: 'Hello World',comp: ''}},mounted() {},methods: {changeComp() {this.comp = null;this.comp = 'thewelcome'}}
}
</script>
但是呢 当点击按钮只会运行一次mounted
原因:这是因为vue为了更新优化,当vue检测到comp变为null,准备销毁当前组件,但是没有真正的执行DOM更新,由于Vue的异步更新机制,comp的值被快速的覆盖为thewelcome,不会真正的销毁组件,TheWelcome组件只是重新渲染,不会触发unmounted和mounted
解决方案:
使用this.$nextTick来进行触发,这个方式确保代码在DOM更新后执行
changeComp() {this.comp = null; // 移除当前组件this.$nextTick(() => {this.comp = 'thewelcome'; // 在下一个 DOM 更新周期重新挂载});
}