Vue-router
1.使用Vue-router
1.1安装路由
npm install -s -g vue-router@4
1.2使用步骤
注意:vue-router必须是4版本以上的否者不能用
1.2.1 创建router.js文件配置
//import引入路由方法
//createRouter创建路由
//createWebHistory路由模式路径(不带#号)
//createWebHashHistory路由模式路径(带#号)
import { createRouter,createWebHistory } from 'vue-router';
//定义路由规则
const routes = [
{path:'/',component:home},
//异步加载(路由懒加载)
{path:'/',component:function(){
return import('../views/my.vue')
}},
]
//创建路由对象
const router = createRouter({
history:createWebHistory(process.env.BASE_URL),
routes
})
export defalt router
1.2.2 main.js项目运行入口文件中import引入路由文件use使用路由
createApp(App).use(router).mount('#app')
1.2.3 App.vue主模板文件使用路由标签
<router-link to="/">main</router-link>
<router-view />
router-link
:to属性跳转至,tag属性标签类型
router-view
:当前路径加载的组件
2.路由传值
2.1 hash传值params获取
<router-link :to="`/login/${name}/${id}`"><router-link/>
//路由配置文件
path: '/login/:name/:id',
//组件内mounted方法中params获取值
this.$route.params
2.2 get传值query获取
<router-link :to="`/login?name=${name}&id=${id}`"><router-link/>
//组件内mounted方法中query获取值
this.$route.query
2.3 对象传值 (path name)
<router-link :to="{name:'login',query:{id:id,name:name}}"><router-link/>
<router-link :to="{path:'/login',params:{id:id,name:name}}"><router-link/>
3.编程式路由
3.1 r o u t e 和 route和 route和router的区别
mounted(){
console.log(this.$route)
console.log(this.$router)
}
this.$route路由信息
this.$router全局路由的实例
3.2 this.$route.push
// 字符串
this.$route.push('home')
// 对象
this.$route.push({ path: 'home' })
// 命名的路由
this.$route.push({ name: 'user', params: { userId: '123' }})
// 带查询参数,变成 /register?plan=private
this.$route.push({ path: 'register', query: { plan: 'private' }})
//如果提供了path,params会被忽略
const userId = '123'
this.$route.push({ path: `/user/${userId}` }) // -> /user/123
3.3 this.$route.replace()
跟 router.push
很像,唯一的不同就是,它不会向 history 添加新记录,而是跟它的方法名一样 —— 替换掉当前的 history 记录。
3.4 this.$route.go()
这个方法的参数是一个整数,意思是在 history 记录中向前或者后退多少步,类似 window.history.go(n)
。
// 在浏览器记录中前进一步,等同于 history.forward()
router.go(1)
// 后退一步记录,等同于 history.back()
router.go(-1)
// 前进 3 步记录
router.go(3)
// 如果 history 记录不够用,那就默默地失败呗
router.go(-100)
router.go(100)
4.路由重定向和别名
4.1 重定向
//url路径
redirect: '/login',
//path路径
redirect: { path: '/login' },
//name属性
redirect: { name: 'login' },
//函数返回
redirect: to => {
// 方法接收 目标路由 作为参数
// return 重定向的 字符串路径/路径对象
return '/login'
}
//404页面配置
{
path: '/404',
name: '404',
component: () => import('@/view/404')
},
{
path: '/:pathMatch(.*)',
redirect: '/404'
}
4.2 别名
// 通过/b路径可以访问到/路径,url路径显示的还是/路径
{
path:'/',
component:()=>import(),
alias:'/b'
}
5.导航守卫
5.1 守卫类型
前置钩子函数:router.beforeEach((to,from,next)
后置钩子函数:router.afterEach((to,from)
to : 即将要进入的目标 路由对象
from :当前导航正要离开的路由
next:进行管道中的下一个钩子
//进行管道中的下一个钩子
next()
//中断当前的导航
next(false)
//跳转到一个不同的地址
next('/')
next({path:'/'})
5.2 全局守卫
main.js中设置全局守卫
//使用router实例
router.beforeEach((to, from, next) => {
if (to.path == '/login' || to.path == '/register') {
next()
} else {
alert('您还没有登录请登录')
next('/login')
}
})
5.3 组件守卫
beforeRouteEnter:(to,from,next)=>{}
到达这个组件时
beforeRouteUpdate:(to,from,next)=>{}
更新这个组件时
beforeRouteLeave:(to,from,next)=>{}
离开这个组件时
这三个路由导航守卫to,from,next和全局路由守卫是一样的,但是要注意beforeRouteEnter
中没有this,因为守卫在导航确认前被调用,因此即将登场的新组件还没被创建,但是可以通过next(vm=>{})
来访问vue组件实例,beforeRouteUpdate
和beforeRouteLeave
中有this指针的存在
export default {
name: 'login',
beforeRouteEnter(to, from, next) {
//没有this,通过next函数调用vue组件实例
next((vm) => {
console.log(vm)
})
},
beforeRouteUpdate(to, from, next) {
//下面这两个都可以使用this
this.name = to.query.name
console.log(this)
next()
},
beforeRouteLeave(to, from, next) {
//这个离开守卫通常用来禁止用户在还未保存修改前突然离开
console.log(this)
next(false)
},
}
5.4 路由独享的守卫
beforeEnter:(to,from,next)=>{},用法与全局守卫一致。只是,将其写进其中一个路由对象中,只在这个路由下起作用。
{
path: '/',
component: () => import('../components/home'),
beforeEnter: (to, from, next) => {
alert('非登录状态,不能访问此页面')
next('/login')
},
},
路由获取数据
导航完成后获取数据:created
导航完成前获取数据:beforeRouteEnter
路由元信息
//配置 meta 字段
meta:{键值对}