vue中动态组件component的实际应用

定义

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>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值