序言
開發的時候有時候會遇到一種情況,比如 :點擊這個鏈接跳轉到其他組件的情況,通常會跳轉到新的頁面,但是我們不想跳轉到新頁面,只在當前頁面切換着顯示,那么就要涉及到路由的嵌套了,也可以說是子路由的使用。
在需要嵌套的頁面的路由地址中添加children
屬性,添加對應的路徑
使用方法
rounter.js
代碼如下:
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
import Index from '../views/index.vue'
import a from '../views/a/a'
import b from '../views/b/b'
import c from '../views/c/c'
const routes = [
{
path: '/',
name: 'index',
component: Index,
children: [
{ path: 'a', name: 'a', component: a },
{ path: 'b', name: 'b', component: b },
{ path: 'c', name: 'c', component: c },
{ path: '/', name: 'a', component: a}
// path表示的為 / 默認路徑顯示的是a組件
],
},
]
const router = new VueRouter({
routes,
})
// 取消 路由重復 報錯
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
return originalPush.call(this, location).catch(err => err)
}
export default router
主頁面index.js
代碼如下:
<template>
<div style="background-color:#F5F7F9;height:100%" class="flex">
<!-- 側面菜單 -->
<Menu idDivProp="shift" v-on:address="getAddress"></Menu>
<router-view></router-view>
</div>
</template>
<script>
import Menu from '../components/menu'
export default {
components: {
Menu,
},
data() {
return {
}
},
methods: {
//頁面跳轉
jumpPage(value) {
this.$router.push(value)
},
getAddress(value) {
this.jumpPage(value)
},
},
created() {},
mounted() {},
}
</script>
<style lang="scss" scoped></style>
在組件Menu
中返回給主頁面index.js地址參數用於切換router-view
menu組件
返回給主頁面index.js的地址參數的方法:
deliverAddress(value) {
let key = value.key
switch (key) {
case '1': //點擊a
this.$emit('address', 'a')
break
case '2': //點擊b
this.$emit('address', 'b')
break
case '3': //點擊c
this.$emit('address', 'c')
break
default:
break
}
},
最后
也可使用組件router-link
跳轉,具體可參考如下文獻: