vue3 动态组件,keep-alive

完整代码

<script setup>
import ComponentA from './components/ComponentA.vue'
import ComponentB from './components/ComponentB.vue'
import ComponentC from './components/ComponentC.vue'
import ComponentD from './components/ComponentD.vue'

import { ref, computed } from 'vue'

// 动态组件映射
const componentMap = {
  ComponentA,
  ComponentB,
  ComponentC,
  ComponentD
}

const tabs = [
  {
    name: 'ComponentA,
    label: '组件A'
  },
  {
    name: 'ComponentB',
    label: '组件B'
  },
  {
    name: 'ComponentC',
    label: '组件C'
  },
  {
    name: 'ComponentD',
    label: '组件D'
  }
]
const currentComponent = ref('ComponentA')
const dynamicMessage = ref('Hello from Parent Component!')

// 计算属性,返回当前的组件对象
const CurrentComponent = computed(() => componentMap[currentComponent.value])

const onChange = (name) => {
  currentComponent.value = name
}
</script>

<template>
  <div class="detail-view">
    <div class="header">
      <div
        v-for="(item, index) in tabs"
        :key="index"
        class="tab"
        :class="{ active: item.name === currentComponent }"
        @click="onChange(item.name)"
      >
        <div class="icon"></div>
        <div class="text">{{ item.label }}</div>
      </div>
    </div>

    <keep-alive>
      <component :is="CurrentComponent" :message="dynamicMessage" class="container" />
    </keep-alive>
  </div>
</template>

<style lang="scss" scoped>
.detail-view {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.header {
  display: flex;
  align-items: center;

  gap: 8px;

  padding: 8px 12px;
  border-bottom: 1px solid rgba(187, 187, 187, 0.19);

  .tab {
    width: 48px;
    height: 24px;

    display: flex;
    justify-content: center;
    align-items: center;

    font-size: 12px;
    font-weight: bold;

    border: 1px solid #f2f0f7;
    border-radius: 24px;
    background-color: #f9f8fe;

    &.active {
      color: #fff;
      background-color: #9965f7;
    }
  }
}

.container {
  flex: 1;
}
</style>

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值