动态切换组件,结合 v-for 渲染标签页标题。
当前位置:首页 > VUE

vue实现tab多页

2026-01-23 06:17:39VUE

Vue 实现 Tab 多页

使用动态组件切换

通过 Vue 的 <component :is="currentTab"> 动态切换组件,结合 v-for 渲染标签页标题。

<template>
  <div>
    <div class="tabs">
      <button 
        v-for="tab in tabs" 
        :key="tab.name"
        @click="currentTab = tab.component"
        :class="{ active: currentTab === tab.component }"
      >
        {{ tab.name }}
      </button>
    </div>
    <component :is="currentTab" />
  </div>
</template>

<script>
import Tab1 from './Tab1.vue';
import Tab2 from './Tab2.vue';

export default {
  data() {
    return {
      currentTab: 'Tab1',
      tabs: [
        { name: 'Tab 1', component: 'Tab1' },
        { name: 'Tab 2', component: 'Tab2' }
      ]
    };
  },
  components: { Tab1, Tab2 }
};
</script>

<style>
.tabs button.active {
  background: #ddd;
}
</style>

使用路由实现多页

结合 Vue Router 实现 URL 驱动的 Tab 切换,适合需要保存页面状态的场景。

// router.js
const routes = [
  { path: '/tab1', component: () => import('./Tab1.vue') },
  { path: '/tab2', component: () => import('./Tab2.vue') }
];
<template>
  <div>
    <router-link to="/tab1">Tab 1</router-link>
    <router-link to="/tab2">Tab 2</router-link>
    <router-view></router-view>
  </div>
</template>

使用状态管理保存数据

通过 Vuex 或 Pinia 管理 Tab 数据,确保切换时状态不丢失。

// store.js (Pinia 示例)
import { defineStore } from 'pinia';

export const useTabStore = defineStore('tabs', {
  state: () => ({
    activeTab: 'Tab1',
    tabData: {}
  })
});
<template>
  <button @click="store.activeTab = 'Tab1'">Tab 1</button>
  <button @click="store.activeTab = 'Tab2'">Tab 2</button>
  <component :is="store.activeTab" />
</template>

<script setup>
import { useTabStore } from './store';
const store = useTabStore();
</script>

响应式 Tab 容器

通过 CSS 和动态样式实现响应式 Tab 布局,适应不同屏幕尺寸。

.tabs {
  display: flex;
  overflow-x: auto;
}
.tab-content {
  padding: 12px;
}
@media (max-width: 600px) {
  .tabs button {
    padding: 8px 12px;
    font-size: 14px;
  }
}

动画过渡效果

添加 Vue 过渡动画使 Tab 切换更平滑。

vue实现tab多页

<transition name="fade" mode="out-in">
  <component :is="currentTab" />
</transition>
.fade-enter-active, .fade-leave-active {
  transition: opacity 0.3s;
}
.fade-enter, .fade-leave-to {
  opacity: 0;
}

标签: 多页vue
分享给朋友:

相关文章

vue实现slidetoggle

vue实现slidetoggle

Vue 实现 SlideToggle 效果 SlideToggle 是一种常见的交互效果,元素以滑动方式展开或收起。以下是几种实现方法: 使用 CSS Transition 和 v-show 通过…

vue实现Pop

vue实现Pop

Vue 实现 Popover 组件的方法 使用 Vue 内置指令 v-show/v-if 和事件监听 通过 Vue 的指令和事件绑定实现基础的 Popover 功能。定义一个布尔值控制 Popover…

vue系统实现

vue系统实现

Vue 系统实现的关键步骤 项目初始化与配置 使用 Vue CLI 或 Vite 创建项目,安装核心依赖(如 Vue 3、Vue Router、Pinia)。配置开发环境(如 ESLint、Prett…

vue 实现路径

vue 实现路径

在 Vue 中实现路径管理通常涉及路由配置、动态路由、嵌套路由等场景,以下是具体实现方法: 基础路由配置 安装 Vue Router 并创建路由实例: npm install vue-router…

用vue实现echarts

用vue实现echarts

使用 Vue 实现 ECharts 安装依赖 在 Vue 项目中安装 ECharts 和 Vue-ECharts(官方推荐的 Vue 封装库): npm install echarts vue-ec…

vue实现type切换

vue实现type切换

Vue 实现 Type 切换的实现方法 在 Vue 中实现 Type 切换功能可以通过动态组件、条件渲染或路由切换等方式实现。以下是几种常见方法: 使用 v-if 或 v-show 条件渲染 通过绑…