Vue——路由案例

59 阅读1分钟

效果图:实现点击那个按钮,下面的页面就出现哪一个。

image.png

image.png

如何实现:

第一步:在router.index.js文件中注册路由(home)和子路由(a,b,c,d)

import Vue from 'vue'
import VueRouter from 'vue-router'
import home from '../views/home.vue'
Vue.use(VueRouter)
// 注册路由
const routes = [
  {
    path: '/',
    name: 'home', 
    component: home,
    redirect:"./a",
    // 注册子路由
    children:[
      {
        path:"/a",
        component:()=>import("../views/Home/a/a.vue")
      },
      {
        path:"/b",
        component:()=>import("../views/Home/b/b.vue")
      },
      {
        path:"/c",
        component:()=>import("../views/Home/c/c.vue")
      },
      {
        path:"/d",
        component:()=>import("../views/Home/d/d.vue")
      }
    ]

  }
]

// 配置路由规则
const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

export default router

第二步:views文件中添加路由文件

注意:

  1. componet文件是用来写组件文件的
    
  2. Home文件是用来写路由文件的
    

image.png

第三步:写路由文件、组件文件

组件文件:

<template>
  <div class="nav">
    <router-link to="/a">a</router-link>
    <router-link to="/b">b</router-link>
    <router-link to="/c">c</router-link>
    <router-link to="/d">d</router-link>
  </div>
</template>

<script>
export default {

}
</script>

<style scoped="scoped" lang="scss">
.nav{
    display: flex;
    width: 100%;
    height: 50px;
    justify-content: flex-start;
    flex-wrap: nowrap;
    background-color: cadetblue;
    a{
        display: block;
        // margin-left: 20px;
        text-decoration: none;
        line-height: 50px;
        width: 50px;
        &:hover{
            background-color: crimson;
        }
    }
    
}
</style>

路由文件:

注意:这里的Nav标签就是我们前面写的组件,b、c、d路由文件与a一样的。 image.png