Vue的生命周期mounted(Vue3的声明周期onMounted)执行多次问题
标题 | Vue的生命周期mounted执行多次 |
---|---|
作者 | walton |
时间 | 2022-07-12 |
Vue | ^3.2.25 |
Ant Design Vue | ^3.2.4 |
一、 问题现象
在使用Ant Design Vue 制作后台管理系统时,发现视图的mounted生命周期函数会执行多次
二、问题原因
- 在onMounted声明周期中打印日志,观察控制台(执行了4次)
onMounted(() => {
console.log('mounted-----渲染次数')
})
- 为什么是4次?
观察发现,页面上有4个页签,可能由此导致,查看页签的代码(tabs.vue)
此处的router-view 放在了v-for内,会多次渲染执行(有多少个页签就会执行多少次)
<template>
<a-tabs
v-model:activeKey="tabInfo.activeKey"
class="tabs-container"
size="small"
hide-add
type="editable-card"
@change="tabChange"
@edit="tabEdit"
>
<a-tab-pane
v-for="pane in tabInfo.panes"
:key="pane.key"
:tab="pane.title"
:closable="pane.closable"
class="pane"
>
<!-- 此处的router-view 放在了v-for内,会多次渲染执行 -->
<router-view></router-view>
</a-tab-pane>
</a-tabs>
</template>
三、解决方案
将v-for循环内的router-view 放在for循环之外即可
<template>
<a-tabs
v-model:activeKey="tabInfo.activeKey"
class="tabs-container"
size="small"
hide-add
type="editable-card"
@change="tabChange"
@edit="tabEdit"
>
<a-tab-pane
v-for="pane in tabInfo.panes"
:key="pane.key"
:tab="pane.title"
:closable="pane.closable"
class="pane"
>
</a-tab-pane>
</a-tabs>
<div class="tabs-content">
<!-- 将router-view 放在了v-for外,解决mounted多次渲染执行 -->
<router-view></router-view>
</div>
</template>