定义
vue提供了一个内置的组件,专门用来实现动态组件的渲染:通过 is 属性动态指定要渲染的组件
<component is="组件名称"></component>
使用
单独使用component 会频繁的触发组件的创建和销毁,性能不好,且会丢失组件状态,所以一般搭配keepalive组件使用,缓存组件状态,用于切换显示的组件会触发activated和deactivated两个生命周期函数, 组件激活时调用activated 组件冻结时调用deactivated
<template>
<div class="p-resouerce">
<div class="tabs">
<div class="tabs__nav">
<div
v-for="(item, index) in tabList"
:key="index"
class="tab"
:class="[{ 'tab--selected': tab === item.value }]"
@click="changeTab(item.value)"
>
{{ item.name }}
</div>
</div>
<div class="tabs__content">
<transition name="fade-transform" mode="out-in">
<keep-alive>
<component :is="currentView"></component>
</keep-alive>
</transition>
</div>
</div>
</div>
</div>
</template>
<script>
import one from './one.vue';
import two from './two.vue';
import three from './three.vue';
export default {
name: 'Resource',
data() {
return {
tab: 1,
tabList: [
{
value: 1,
name: 'tab页1',
path: 'one',
type: 'NetworkDis',
},
{
value: 2,
name: 'tab页2',
path: 'two',
type: 'School',
},
{
value: 3,
name: 'tab页3',
path: 'three',
type: 'Platform',
},
],
fromPage: '',
};
},
components: {
one,
two,
three,
},
computed: {
currentView() {
let path = '';
this.tabList.forEach((item) => {
if (item.value === this.tab) {
path = item.path;
}
});
return path;
},
},
methods: {
// 返回
back() {
this.$router.go(-1);
},
// 切换tab
changeTab(value) {
this.tab = value;
},
},
beforeRouteLeave(to, from, next) {
if (['/lesson'].includes(to.path)) {
this.$store.dispatch('lesson/initState');
}
next();
},
created() {
const { type, fromPage } = this.$route.query;
this.fromPage = fromPage;
}
};
</script>
<style lang='scss' scoped>
</style>
|