动态组件的切换方式

130 阅读1分钟

前言:想实现的功能是点击上面的商品详情/商品评价下面的组件也跟着切换

我们很容易想到v-if的切换方式 其实还有一种方式<component>标签也能帮助我们更好地完成这一功能 且这种方式更为推荐 image.png

1.v-if

2.<component :is=''></component>

is的值是哪个组件名就显示哪个组件

<template>
  <div class="goods-tabs">
    <nav>
      <a @click='toggle("GoodsDetail")' :class="{active: componentName === 'GoodsDetail'}" href="javascript:;">商品详情</a>
      <a @click='toggle("GoodsComment")' :class="{active: componentName === 'GoodsComment'}" href="javascript:;">商品评价<span>(500+)</span></a>
    </nav>
    <!-- 基于动态组件控制组件的切换 -->
    <component :is='componentName'></component>
  </div>
</template>
<script>
  import GoodsDetail from './goods-detail.vue'
  import GoodsComment from './goods-comment.vue'
  import { ref } from 'vue'
  export default {
   name: 'GoodsTabs',
   components: { GoodsDetail, GoodsComment },
   setup () {
    // 当前组件的名称
    const componentName = ref('GoodsDetail')
    const toggle = (name) => {
      componentName.value = name
    }
    return { toggle, componentName }
   }
 }
</script>