Vue3迁移中v-stepper-vertical切换步骤重复创建组件求助
解决Vue3中v-stepper-vertical切换步骤时子组件重复创建的问题
问题原因
v-stepper-vertical组件默认会在步骤切换时,卸载非激活状态的<v-stepper-vertical-item>内部DOM,导致其中的子组件(比如你的CompA)被销毁。再次切回该步骤时,组件会重新创建,因此created钩子会重复触发。
解决方案:使用<KeepAlive>缓存组件
Vue3内置的<KeepAlive>组件可以缓存不活动的组件实例,而非直接销毁。将需要保留状态的子组件包裹在<KeepAlive>中,即可避免重复创建。
修改步骤1的代码如下:
<v-stepper-vertical-item :complete="step > 1" subtitle="Personal details" title="Step one" value="1" > <KeepAlive> <CompA></CompA> </KeepAlive> <template v-slot:next="{ next }"> <v-btn color="primary" @click="next"></v-btn> </template> <template v-slot:prev></template> </v-stepper-vertical-item>
额外说明
- 缓存范围控制:如果需要缓存多个步骤的组件,可以将整个
<v-stepper-vertical>的默认插槽内容包裹在<KeepAlive>中,但更推荐精准缓存需要保留状态的组件,避免不必要的内存占用。 - 激活时的逻辑处理:如果需要在组件每次被激活(切回步骤)时执行特定逻辑,可使用Vue3的
onActivated钩子替代created:
<script> export default { name: 'CompA', created() { console.log('组件仅初始化一次') }, activated() { console.log('每次切回步骤1时触发') // 这里可以处理数据更新等逻辑 } } </script>
内容的提问来源于stack exchange,提问作者Abdulkadir Dalga
相关产品推荐
相关产品推荐

