vue-router嵌套路由

2022-06-14  本文已影响0人  itfitness

目录

实现步骤

1.创建pages文件夹

创建pages文件夹用来存放路由页面组件,这里我创建了四个组件,其中Circle和Focus组件属于Home组件


2.配置路由

这里我新建了router文件夹,新建了index.js文件用来配置路由


import Vue  from "vue"
import VueRouter  from "vue-router"
import Home  from "../pages/Home.vue"
import About  from "../pages/About.vue"
import Circle  from "../pages/Circle.vue"
import Foucs  from "../pages/Foucs.vue"
Vue.use(VueRouter)
export default new VueRouter({
    routes:[
        {
            path:"/Home",
            component:Home,
            children:[
                {
                    path:"Circle",
                    component:Circle
                },
                {
                    path:"Foucs",
                    component:Foucs
                }
            ]
        },
        {
            path:"/About",
            component:About
        }
    ]
})
3.使用路由

需要在main.js中引入路由配置文件并使用

import Vue from 'vue'
import App from './App.vue'
import router from "./router/index.js"
Vue.config.productionTip = false

new Vue({
  render: h => h(App),
  router
}).$mount('#app')
4.页面使用

App.vue如下:

<template>
  <div class="container">
      <div class="tab">
          <router-link class="tab-item" active-class="active" to="/Home">首页</router-link>
          <router-link class="tab-item" active-class="active" to="/About">关于</router-link>
      </div>
      <router-view></router-view>
  </div>
</template>

<script>

export default {
  name: 'app',
  components: {
    
  }
}
</script>

<style>
    .container{
        padding: 50px;
    }
    .tab{
        margin-top: 30px;
    }
    .tab-item{
        border-radius: 10px;
        border-width: 2px;
        margin-right: 20px;
        border-style: solid;
        color: #000000;
        border-color: #0074D9;
        text-decoration:none;
        padding: 20px 50px 20px 50px;
    }
    .active{
        color: white;
        background-color: #0074D9;
    }
</style>

Home.vue如下

<template>
    <div>
        <h1>首页</h1>
        <div class="tab">
            <router-link class="tab-item" active-class="active" to="/Home/Circle">圈子</router-link>
            <router-link class="tab-item" active-class="active" to="/Home/Foucs">关注</router-link>
        </div>
        <router-view></router-view>
    </div>
</template>

<script>
    export default {
        
    }
</script>

<style scoped>
    .tab{
        margin-top: 30px;
    }
    .tab-item{
        border-radius: 5px;
        border-width: 1px;
        margin-right: 10px;
        border-style: solid;
        color: #000000;
        border-color: #8F3F71;
        text-decoration:none;
        padding: 10px 30px 10px 30px;
    }
    .active{
        color: white;
        background-color: #8F3F71;
    }
</style>

效果如下


注意

因为我使用的vue版本是2版本因此这里使用的vue-router是3版本

npm i vue-router@3
上一篇 下一篇

猜你喜欢

热点阅读