一、什么是Vue路由
Vue.js 路由允许我们通过不同的 URL 访问不同的内容。
通过 Vue.js 可以实现多视图的单页Web应用(single page web application,SPA)。
二、路由配置 /router/index
1、普通路由配置
{
path: '/user', //配置的路径
name: 'user', //名称
component: () => import('xxx)
}
2、路由传参
{
path:“/product/:id”,
name:"product",
component:xxx
}
<router-link to="/product/abc">
在页面中获取:$route.params.id
}
三、404页面
<template>
<div>
<h1>404</h1>
<p>您的页面被外星人绑架了!</p>
<router-link to="/">回首页</router-link>
</div>
</template>
// 404的path为* 配置在最后面
{
path: "*",
name: "nomatch",
component: () => import('../views/NoMatch.vue')
}
四、编程式路由跳转
- 前进 forward() go(1)
- 后退 go(-1) back()
- 切换路由 push("/about")
- 替换路由 replace("/about")
三、路由信息
- 路由参数 params
- 查询 query
- 地址 path
- 全地址 fullPath
- 名称 name
<template>
<div>
<h1>产品页面{{$route.params.id}}</h1>
<p>查询参数:{{$route.query}}</p>
<p>哈希值:{{$route.hash}}</p>
<p>全地址:{{$route.fullPath}}</p>
<p>地址:{{$route.path}}</p>
<p>名称:{{$route.name}}</p>
<button @click='$router.back()'>返回</button>
</div>
<template>
四、路由守卫
(1)组件内部
进入前:beforeRouterEnter(to,from,next)
to 要进入的路由
from 从哪个页面进入
next 下一步
next()进入to页面
next(true)进入to页面
next(false)不跳转
next(“/login”)跳转到登录
离开前 :beforeRouterLeave
更新前:beforeRouterUpdate
(2)全局
beforeEach((to,from,next)=>{})afterEach
(3) 独享
beforeEnter()
五、路由参数查询
传递
next("/login?redirect=/cart")获取
var redirect = this.$route.query.redirect||'/user'