前端路由
vue-router
vue-router安装
npm i vue-router@3.5.2 -S
创建路由模块
再src源代码目录下,新建router/index.js路由模块,并初始化如下代码:
// 1、导入Vue和VueRouter
import Vue from 'vue'
import VueRouter from 'vue-router'
// 2、安装VueRouter插件
Vue.use(VueRouter)
// 3、创建路由的实例对象
const router = new VueRouter({
})
// 4、向外共享router
export default router
挂载路由模块
再main.js中将vue-router挂在到vue中
import router from '@/router/index.js'
new Vue(){
render:h=>h(App);
router
}
路由的基本使用
//App.vue
<router-link to="/home"></router-link>
//占位符
<router-view></router-view>
//index.js
import Home from '@/components/Home.vue'
const router = new VueRouter({
//routes是一个数组,用来描述地址与组件之间的关系---路由规则
routes:[
{path:'/' , redirect:'/home'},
{path:'/home' , component:Home}
]
})
嵌套路由
//index.js
const router = new VueRouter({
//routes是一个数组,用来描述地址与组件之间的关系---路由规则
routes:[
{path:'/' , redirect:'/home'},
{
path:'/home' ,
component:Home,
redirect:'/home/tab' //重定向
children:[ //子路由规则
{path:'',component:Tab} //默认子路由
{path:'tab',component:Tab}
]
}]
})
路由传递参数
query
传递参数
to
的字符串写法
<templete>
<router-link
:to="`/home/message/detail?id=${m.id}&title=${m.title}`">
{{m.title}}
</router-link>
</templete>
to
的对象写法
<templete>
<router-link
:to="{
name: 'detail',
query: {
id: m.id,
title: m.title,
},
}">
{{ m.title }}
</router-link>
</templete>
或者使用path
<templete>
<router-link
:to="{
path: '/home/message/detail',
query: {
id: m.id,
title: m.title,
},
}">
{{ m.title }}
</router-link>
</templete>
params
传递参数
to
的字符串写法
<router-link
:to="`/home/message/detail/${m.id}/${m.title}`">
{{m.title}}
</router-link>
to
的对象写法
⚠️ 此写法必须使用name不能使用path属性 !
<router-link
:to="{
name: 'detail',
params: {
id: m.id,
title: m.title,
},
}">
{{ m.title }}
</router-link>
编程式导航
push
this.$router.push({
name: "detail",
query: {
id: m.id,
title: m.title,
},
});
replace
this.$router.replace({
name: "detail",
query: {
id: m.id,
title: m.title,
},
});
go
//-1表示往后推一层
this.$router.go(-1);
导航守卫
可以控制路由的访问权限
全局前置守卫
const router = new VueRouter({...})
//调用路由实例对象的beforeEach方法
//每次发生路由导航跳转的时候,都会自动触发cb这个回调函数
router.beforeEach((to,from,next)=>{
//to是将要访问的路由的信息对象
//from是将要离开的路由的信息对象
//next是一个函数,调用next()表示放行,允许这次路由导航
})