文章目录
前言
在之前的一级路由中,我们解决了原生中的抖动问题,以及代码冗余问题,但是现在还有一个问题没有解决,那就是如果有多个需要跳转的那该怎么办呢?
一、多级路由的作用?
其实很简单,只要会以一级路由那么后面的多级路由也不是什么难问题,主要我们得会使用路由的嵌套,所谓嵌套就是一个路由规则里面可能还有一个路由规则,依次进行。
二、使用步骤
1.引入库
还是一样的操作,Vue2的下载如下版本:
npm i vue-router@3
Vue3的下载如下版本:
npm i vue-router@4
2.搭建环境
代码如下(示例):
export default new Vuerouter({
routes:[
{
path:'/liebiao',
component: liebiao,
children:[//多级路由
{
name:'zhanshi',
path:'zhanshi/:id/:name',
component:zhanshi,
// props:true//prpos为真只能接收paprem的参数
// prpos的第二种写法,不管是query参数还是params参数都可以接收(常用)
props($route){//这里也可以解构赋值{params}
return {
iid:$route.params.id,
nname:$route.params.name
}
}
}
]
},
{
path:'/zhuye',
component:zhuye,
}
]
})
main.js文件配置:
import Vue from 'vue'
import App from './App.vue'
import Vuerouter from 'vue-router'
import router from './router/index.js'
Vue.config.productionTip = false
Vue.use(Vuerouter)
new Vue({
el:'#app',
render: h => h(App),
router:router,
})
然后就是所对应的各个组件:
<template>
<div>
<ul>
<li>我是列表页</li>
<li><router-link :to="{
//path:'/liebiao/zhanshi',
name:'zhanshi',
/*query:{
id:1,
name:'你的名字'
},*/
params:{
id:1,
name:'你的名字'
}
}">点击去展示</router-link></li>
</ul>
<router-view></router-view>
</div>
</template>
<script>
export default {
name:'liebiao'
}
</script>
<style>
</style>
<template>
<ul>
<li>我来展示</li>
<li>{{$route.params.id}}</li>
<li>{{$route.params.name}}</li>
<li>{{name}}</li>
<li>{{id}}</li>
<li>{{iid}}</li>
<li>{{nname}}</li>
</ul>
</template>
<script>
export default {
name:'zhanshi',
mounted(){
console.log(this);
},
props:['name','id','iid','nname']
}
</script>
<style>
</style>
<template>
<div>我是主页</div>
</template>
<script>
export default {
name:'zhuye'
}
</script>
<style>
</style>
最终看一下运行效果:
总结
本次主要的使用了多级路由来实现多级切换效果,主要就是在一级路由的基础上配置children属性,他是一个数组,里面都是他的下级路由