动态切换组件,结合 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 切换更平滑。

<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实现tab多页

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

相关文章

vue登录业务的实现

vue登录业务的实现

实现登录业务的基本流程 在Vue中实现登录业务通常涉及前端界面设计、表单验证、API请求交互、状态管理以及路由控制等环节。以下是核心实现步骤: 登录表单设计与验证 创建包含用户名和密码输入框的登录…

vue实现用户信息表

vue实现用户信息表

Vue 实现用户信息表的方法 使用 Vue CLI 创建项目 安装 Vue CLI 并初始化项目: npm install -g @vue/cli vue create user-info-tab…

vue优秀实现

vue优秀实现

Vue.js 优秀实现方法 响应式数据管理 使用 Vue 的 ref 和 reactive 处理基础类型和对象类型数据,结合 computed 计算属性优化渲染性能。对于复杂状态,推荐 Pinia 替…

vue实现弹窗

vue实现弹窗

Vue 实现弹窗的常见方法 使用组件化方式封装弹窗 创建一个独立的弹窗组件(如 Modal.vue),通过 v-if 或 v-show 控制显示隐藏: <template> <…

vue 实现复选

vue 实现复选

Vue 实现复选功能 在 Vue 中实现复选功能可以通过多种方式完成,以下是常见的几种方法: 使用 v-model 绑定数组 通过 v-model 绑定一个数组,可以自动收集用户选择的复选框值。…

vue实现贴图

vue实现贴图

Vue 实现贴图功能 在Vue中实现贴图功能通常涉及将图片动态添加到指定位置或元素上。以下是几种常见实现方式: 使用v-bind动态绑定图片 通过数据驱动的方式动态更换图片源: <tem…