elementui 的 el-tab 会同时加载几个tab,可能需求想切换tab时才去调用接口等,当然可以用v-if去控制,但是这样每次都重新渲染,用户体验不好,没法缓存数据。如果想缓存和按需加载,可以尝试使用如下方法:
优化前:
<template>
<el-tabs v-model="activeName" @tab-click="handleClick">
<el-tab-pane label="用户管理" name="first">
<UserManage />
</el-tab-pane>
<el-tab-pane label="配置管理" name="second">
<ConfigManage />
</el-tab-pane>
</el-tabs>
</template>
<script>
import UserManage from './component/UserManage'
import ConfigManage from './component/ConfigManage'
export default {
components: { UserManage, ConfigManage },
data() {
return {
activeName: 'first'
};
},
methods: {
handleClick(tab, event) {
console.log(tab, event);
}
}
};
</script>
优化后:
方案一:直接用lazy属性
方案二:组件懒加载
方案三:如下,其实是组件懒加载+动态组件,直接用方案二就行了,方案三有点画蛇添足的意思。。。
<template>
<el-tabs v-model="activeName" @tab-click="handleClick">
<el-tab-pane label="用户管理" name="first">
<UserManage />
</el-tab-pane>
<el-tab-pane label="配置管理" name="second">
<component :is="configManageCom" />
</el-tab-pane>
</el-tabs>
</template>
<script>
import UserManage from './component/UserManage'
export default {
components: {
UserManage,
ConfigManage: () => import(/* webpackPrefetch: true */ './component/ConfigManage')
},
data() {
return {
activeName: 'first',
configManageCom: null,
};
},
methods: {
handleClick(tab) {
if (tab.name === 'second') {
this.configManageCom = 'config-manage'
}
}
}
};
</script>