用vue-router给页面添加选项卡

135 阅读1分钟

目标:给下面图片中“用户1”后面添加“用户2”选项卡。 image.png 下图为起始页面: image.png 下图为添加前,项目的完整目录:

image.png

1. 在views文件夹下面新建一个UserTwo.vue文件:

image.png

UserTwo.vue内容如下:

// UserTwo.vue里面的内容

<template>
    <div>
        <h1>这是用户2页面!</h1>
    </div>
</template>

<script>
    export default {
        
    }
</script>

<style lang="scss" scoped>

</style>

2.在router文件夹下的index.js里面导入UserTwo.vue

3.在router文件夹下的index.js里面挂载UserTwo.vue

index.js代码如下:

// index.js里面的内容

import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
import UserOne from '@/views/UserOne.vue'
import UserTwo from '@/views/UserTwo.vue'   //2.导入UserTwo.vue

const routes = [
  {
    path: '/',
    name: 'home',
    component: HomeView
  },
  {
    path: '/about',
    name: 'about',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import(/* webpackChunkName: "about" */ '../views/AboutView.vue')
  },
  {
    path:'/userOne',
    name:'userOne',
    component:UserOne
  },
  //3.挂载UserTwo.vue
  {
    path:'/userTwo',
    name:'userTwo',
    component:UserTwo
  }
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})

export default router

4.在App.vue里面引用userTwo

App.vue代码如下:

// App.vue里面的内容

<template>
  <nav>
    <router-link to="/">首页</router-link> |
    <router-link to="/about">关于</router-link> |
    <router-link to='/userOne'>用户1</router-link>  |
    <router-link to='/userTwo'>用户2</router-link>  <!-- //4.引用userTwo -->
  </nav>
  <router-view/>
</template>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
}

nav {
  padding: 30px;
}

nav a {
  font-weight: bold;
  color: #2c3e50;
}

nav a.router-link-exact-active {
  color: #42b983;
}
</style>

5.到这里添加完成,最终效果如下:

image.png 下图为项目最终目录:

image.png

此文章旨在仅供小白用vue-router给页面添加选项卡,大神勿喷!