search
HomeWeb Front-endVue.jsHow to implement tab components and multi-tab pages in Vue?

With the continuous updating of front-end technology, Vue, as a popular front-end framework, has become the first choice of many developers. In actual projects, it is often necessary to use tab components and multi-tab pages to switch and manage different functional modules. In this article, we will introduce how to use Vue to implement a simple tab component and multi-tab page.

1. Implement a simple tab component

  1. Create a Tab.vue component

Create a Tab.vue component in the project for Displays the tab list and the contents of the currently selected tab page.

<template>
  <div>
    <div class="tab-header">
      <div class="tab-item" 
           v-for="(tab, index) in tabs" 
           :key="index"
           :class="{ active: index === currentIndex }" 
           @click="handleTab(index)">
        {{ tab.title }}
      </div>
    </div>
    <div class="tab-content">
      <slot></slot>
    </div>
  </div>
</template>

<script>
export default {
  name: 'Tab',
  props: {
    tabs: {
      type: Array,
      required: true,
    },
    currentIndex: {
      type: Number,
      default: 0,
    },
  },
  methods: {
    handleTab(index) {
      this.$emit('tabchange', index);
    },
  },
};
</script>

In this component, we use the v-for directive to iterate through the incoming tabs array and render the title of each tab as a tab-item. The currentIndex of the selected tab page will add active class to tab-item to highlight the currently selected tab page. The tab component has its own slot slot, which is used to display the content of the tab page.

  1. Use the Tab component in the parent component

On the page where the tab component needs to be used, import the Tab component and use it in the template to display the tab The page is passed into the Tab component as a member of the tabs array, and the index of the currently selected tab page is specified through the currentIndex property. In addition, listen to the tabchange event in the Tab component to change the value of currentIndex in the parent component to control the currently selected tab page.

<template>
  <div>
    <Tab :tabs="tabs" :currentIndex="currentIndex" @tabchange="handleChange">
      <div v-for="(tab, index) in tabs" :key="index">
        {{ tab.content }}
      </div>
    </Tab>
  </div>
</template>

<script>
import Tab from './Tab.vue';

export default {
  name: 'App',
  components: {
    Tab,
  },
  data() {
    return {
      currentIndex: 0,
      tabs: [
        {
          title: 'tab1',
          content: '这是第一个 tab 页的内容',
        },
        {
          title: 'tab2',
          content: '这是第二个 tab 页的内容',
        },
      ],
    };
  },
  methods: {
    handleChange(index) {
      this.currentIndex = index;
    },
  },
};
</script>

In this parent component, we first need to import the Tab component, and then create the tabs array to store the title and content of each tab page. Two properties, tabs and currentIndex, need to be passed in the template to initialize the Tab component respectively. In the handleChange method, we listen to the tabchange event, so that the value of currentIndex can be updated in the parent component to select different tab pages.

2. Implement multi-tab component

  1. Create page layout and routing configuration

Create a page with multi-tab function in the project. First you need to consider the layout of the page. In this article, we use the Layout component of Element UI to build the page infrastructure, and then complete the routing configuration through Vue Router. In a multi-tab scenario, each tab page can be regarded as a routing page, so corresponding routing information needs to be added to the routing table.

<template>
  <div class="page-container">
    <el-container>
      <el-header>
        <h1 id="pageTitle">{{ pageTitle }}</h1>
      </el-header>
      <el-container>
        <el-aside style="width: 200px; height: 100%">
          <el-menu
            :default-active="activeMenu"
            @select="handleSelect"
            unique-opened
            :collapse="isCollapse">
            <el-submenu v-for="menuGroup in menuList" :key="menuGroup.name" :index="menuGroup.name">
              <template slot="title">
                <i :class="menuGroup.icon"></i>
                <span>{{ menuGroup.title }}</span>
              </template>
              <el-menu-item v-for="menuItem in menuGroup.children" :key="menuItem.path" :index="menuItem.path">
                <i :class="menuItem.icon"></i>
                <span slot="title">{{ menuItem.title }}</span>
              </el-menu-item>
            </el-submenu>
          </el-menu>
        </el-aside>
        <el-main>
          <router-view/>
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>

<script>
export default {
  name: 'PageLayout',
  data() {
    return {
      pageTitle: '多标签页示例',
      menuList: [
        {
          name: 'group1',
          title: '分组 1',
          icon: 'el-icon-s-home',
          children: [
            {
              title: '页面 1',
              path: '/page1',
              icon: 'el-icon-s-order',
            },
            {
              title: '页面 2',
              path: '/page2',
              icon: 'el-icon-s-data',
            },
          ],
        },
        {
          name: 'group2',
          title: '分组 2',
          icon: 'el-icon-s-management',
          children: [
            {
              title: '页面 3',
              path: '/page3',
              icon: 'el-icon-s-flag',
            },
            {
              title: '页面 4',
              path: '/page4',
              icon: 'el-icon-menu',
            },
          ],
        },
      ],
      activeMenu: '',
      isCollapse: false,
    };
  },
  methods: {
    handleSelect(index) {
      this.activeMenu = index;
      this.$router.push(index);
    },
  },
};
</script>

In the parent component PageLayout.vue, we first set the page title pageTitle, the menu list menuList and the two status values ​​activeMenu and isCollapse for the expansion and closing of the menu. Then the Layout component of Element UI is used to build the basic structure of the page, with the menu bar on the left and the tab content on the right. In the menu component el-menu, we render the menu groups and menu items through the v-for loop. The menu items are bound to the corresponding routing paths. When the menu items are clicked, the handleSelect method is triggered and the routing path is passed into $router. Jump to the corresponding page in the push method. In this component we need to use router-view to display the corresponding routing component.

  1. Implement the Tab component and multi-tab function

After completing the page layout and routing configuration, we need to implement the tab component and multi-tab function in the page, and Write the corresponding js code. In the multi-tab function, you first need to implement the tab bar component TabBar.vue, which is used to display the title of each tab and control the addition and deletion of tabs.

<template>
  <div class="tab-bar" :class="{ fixed: isFixed }">
    <div class="tab-bar-content">
      <div v-for="(tab, index) in tabs" :key="index" class="tab-item" :class="{ active: currentIndex === index }" @click="handleChange(index)">
        {{ tab.title }}
        <i class="el-icon-close" @click.stop="handleRemoveTab(index)"></i>
      </div>
      <i class="el-icon-circle-plus add-tab-btn" @click.stop="handleAddTab"></i>
    </div>
  </div>
</template>

<script>
export default {
  name: 'TabBar',
  props: {
    tabs: {
      type: Array,
      required: true,
    },
    currentIndex: {
      type: Number,
      default: 0,
    },
    isFixed: {
      type: Boolean,
      default: false,
    },
  },
  methods: {
    handleChange(index) {
      this.$emit('tabchange', index);
    },
    handleAddTab() {
      this.$emit('addtab');
    },
    handleRemoveTab(index) {
      this.$emit('removetab', index);
    },
  },
};
</script>

In this component, we render the title of each tab as a tab-item by using a v-for loop to render the incoming tabs array. The selected tab page will add active class to tab-item to highlight the currently selected tab page. The tab-bar component comes with three events: tabchange is used to listen for tab switching events, addtab and removetab are used to listen for tab addition and removal events, so as to update the value of the tabs array in the parent component.

In the parent component PageLayout.vue, we need to add the TabBar component below the page structure, pass in the tabs and currentIndex properties, and then update the tabs array in the corresponding event method so that the operations can correspond tab page.

<template>
  <div class="page-container">
    ...
    <el-main>
      <tab-bar :tabs="tabs" :currentIndex="currentIndex" :isFixed="isFixed" @tabchange="handleChange" @addtab="handleAddTab" @removetab="handleRemoveTab"/>
      <router-view v-if="$route.meta.keepAlive"/>
      <keep-alive>
        <router-view v-if="!$route.meta.keepAlive"/>
      </keep-alive>
    </el-main>
  </div>
</template>

<script>
import TabBar from '../components/TabBar.vue';

export default {
  name: 'PageLayout',
  components: {
    TabBar,
  },
  data() {
    return {
      tabs: [
        {
          title: '首页',
          path: '/',
        },
      ],
      currentIndex: 0,
      isFixed: false,
    };
  },
  created() {
    this.$router.afterEach((to, from) => {
      const index = this.tabs.findIndex(tab => tab.path === to.path);
      if (index !== -1) {
        this.currentIndex = index;
        this.isFixed = false;
      } else {
        this.addTab(to);
      }
    });
  },
  methods: {
    handleChange(index) {
      this.$router.push(this.tabs[index].path);
    },
    handleAddTab() {
      const isExist = this.tabs.find(tab => tab.path === this.$route.path);
      if (!isExist) {
        this.tabs.push({
          title: this.$route.meta.title || '',
          path: this.$route.path,
        });
        this.currentIndex = this.tabs.length - 1;
        this.isFixed = false;
      } else {
        this.currentIndex = this.tabs.indexOf(isExist);
        this.isFixed = false;
      }
      this.$router.push(this.$route.path);
    },
    handleRemoveTab(index) {
      const targetTab = this.tabs[index];
      const targetPath = targetTab.path;
      this.tabs.splice(index, 1);
      if (targetPath === this.$route.path) {
        const lastIndex = this.tabs.length - 1;
        const lastTab = this.tabs[lastIndex];
        this.currentIndex = lastIndex;
        this.$router.push(lastTab.path);
      } else {
        this.currentIndex = this.tabs.findIndex(tab => tab.path === this.$route.path);
      }
    },
  },
};
</script>

In PageLayout.vue, we first created the tabs array to store the routing information of each tab page. In the created hook function, we listen for changes in the current route and find the corresponding tab route in the tabs array. If it exists, navigate directly to the corresponding tab, otherwise add the current route as a new tab. In the handleAddTab method, if the tab corresponding to the current route already exists, select the existing tab directly, otherwise add a new tab to the tabs array. In the handleRemoveTab method, we use the splice method of the array to delete the existing tab, locate the currently selected tab in the tabs array, and update the jump information of currentIndex and $router.

3. Summary

In this article, we introduce how to use the Vue framework and related plug-ins to implement the tab component and multi-tab page functions. During the actual implementation process, components or codes need to be flexibly adjusted according to specific scenarios to better adapt to actual project needs. In general, the tab component and multi-tab function can provide better usability and user experience for the project, and better solve the architectural problems of the front-end page.

The above is the detailed content of How to implement tab components and multi-tab pages in Vue?. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Vue.js and the Frontend: A Deep Dive into the FrameworkVue.js and the Frontend: A Deep Dive into the FrameworkApr 22, 2025 am 12:04 AM

Vue.js is loved by developers because it is easy to use and powerful. 1) Its responsive data binding system automatically updates the view. 2) The component system improves the reusability and maintainability of the code. 3) Computing properties and listeners enhance the readability and performance of the code. 4) Using VueDevtools and checking for console errors are common debugging techniques. 5) Performance optimization includes the use of key attributes, computed attributes and keep-alive components. 6) Best practices include clear component naming, the use of single-file components and the rational use of life cycle hooks.

The Power of Vue.js on the Frontend: Key Features and BenefitsThe Power of Vue.js on the Frontend: Key Features and BenefitsApr 21, 2025 am 12:07 AM

Vue.js is a progressive JavaScript framework suitable for building efficient and maintainable front-end applications. Its key features include: 1. Responsive data binding, 2. Component development, 3. Virtual DOM. Through these features, Vue.js simplifies the development process, improves application performance and maintainability, making it very popular in modern web development.

Is vue.js better than React?Is vue.js better than React?Apr 20, 2025 am 12:05 AM

Vue.js and React each have their own advantages and disadvantages, and the choice depends on project requirements and team conditions. 1) Vue.js is suitable for small projects and beginners because of its simplicity and easy to use; 2) React is suitable for large projects and complex UIs because of its rich ecosystem and component design.

Vue.js's Function: Enhancing User Experience on the FrontendVue.js's Function: Enhancing User Experience on the FrontendApr 19, 2025 am 12:13 AM

Vue.js improves user experience through multiple functions: 1. Responsive system realizes real-time data feedback; 2. Component development improves code reusability; 3. VueRouter provides smooth navigation; 4. Dynamic data binding and transition animation enhance interaction effect; 5. Error processing mechanism ensures user feedback; 6. Performance optimization and best practices improve application performance.

Vue.js: Defining Its Role in Web DevelopmentVue.js: Defining Its Role in Web DevelopmentApr 18, 2025 am 12:07 AM

Vue.js' role in web development is to act as a progressive JavaScript framework that simplifies the development process and improves efficiency. 1) It enables developers to focus on business logic through responsive data binding and component development. 2) The working principle of Vue.js relies on responsive systems and virtual DOM to optimize performance. 3) In actual projects, it is common practice to use Vuex to manage global state and optimize data responsiveness.

Understanding Vue.js: Primarily a Frontend FrameworkUnderstanding Vue.js: Primarily a Frontend FrameworkApr 17, 2025 am 12:20 AM

Vue.js is a progressive JavaScript framework released by You Yuxi in 2014 to build a user interface. Its core advantages include: 1. Responsive data binding, automatic update view of data changes; 2. Component development, the UI can be split into independent and reusable components.

Netflix's Frontend: Examples and Applications of React (or Vue)Netflix's Frontend: Examples and Applications of React (or Vue)Apr 16, 2025 am 12:08 AM

Netflix uses React as its front-end framework. 1) React's componentized development model and strong ecosystem are the main reasons why Netflix chose it. 2) Through componentization, Netflix splits complex interfaces into manageable chunks such as video players, recommendation lists and user comments. 3) React's virtual DOM and component life cycle optimizes rendering efficiency and user interaction management.

The Frontend Landscape: How Netflix Approached its ChoicesThe Frontend Landscape: How Netflix Approached its ChoicesApr 15, 2025 am 12:13 AM

Netflix's choice in front-end technology mainly focuses on three aspects: performance optimization, scalability and user experience. 1. Performance optimization: Netflix chose React as the main framework and developed tools such as SpeedCurve and Boomerang to monitor and optimize the user experience. 2. Scalability: They adopt a micro front-end architecture, splitting applications into independent modules, improving development efficiency and system scalability. 3. User experience: Netflix uses the Material-UI component library to continuously optimize the interface through A/B testing and user feedback to ensure consistency and aesthetics.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools