Vue切换Tab component动态渲染组件

使用 Vue 的 v-if 和 component 进行条件渲染

v-ifcomponent 是 Vue 中用于条件渲染组件的两种不同方式,它们有以下区别:

条件判断方式不同:

  • v-if: v-if 是一种指令,它直接根据条件的真假来决定是否渲染一个元素或组件。如果条件为真,则渲染该元素或组件,如果条件为假,则从 DOM 中移除该元素或组件。

  • component: component 是一个内置组件标签,通过动态地绑定 :is 属性来指定要渲染的组件。它根据绑定的组件名来动态切换和渲染不同的组件。

渲染时机不同:

  • v-if: 使用 v-if 时,当条件变为真时,Vue 会创建和挂载元素或组件。当条件变为假时,Vue 会销毁对应的元素或组件。

  • component: component 标签在初始化时就会渲染,但是根据 :is 属性绑定的组件名来决定显示哪个组件。通过改变 :is 绑定的值,可以实现动态切换组件。

性能和渲染方式不同:

  • v-if: 当条件为假时,使用 v-if 的元素或组件会被完全从 DOM 中移除,这样可以节省一些渲染和交互开销。但是,频繁切换 v-if 条件可能导致 DOM 的频繁插入和移除,可能影响性能。

  • component: 使用 component 标签的动态渲染方式,组件在切换时是通过 Vue 的组件系统进行的,因此组件在销毁和重新创建之间会保留其状态。这意味着组件的状态会得到保留,不会像 v-if 那样频繁地销毁和创建,从而在某些场景下可能有更好的性能。

示例:Tab 切换组件

Vue切换Tab component动态渲染组件_第1张图片

以下是一个使用 component 实现 Tab 切换组件的示例:

<template>
  <div class="container">
    <div class="tabs">
      <div v-for="(item, index) in tabs" :class="[active === index ? 'active' : '']" @click="toggleComponent(index)">
        {{ item.name }}
      div>
    div>
    <div>
    
      <component :is="tabs[active].component">component>
    div>
  div>
template>

<script setup lang="ts">
import A from './views/A/index.vue'
import B from './views/B/index.vue'
import C from './views/C/index.vue'
import { ref } from 'vue'

const active = ref(0)

const tabs = [
  {
    name: 'A',
    component: A
  },
  {
    name: 'B',
    component: B
  },
  {
    name: 'C',
    component: C
  }
]

const toggleComponent = (index: number) => {
  active.value = index
}
script>

你可能感兴趣的:(vue.js,javascript,前端)