目录
🐇 全局 beforeEach((to,from,next)=>{}) afterEach
🐇 传递next("/login?redirect=/cart")
🐇 获取var redirect = this.$route.query.redirect||'/user'
🍓
🐇
在前面文章脚手架的介绍中,如果你用vue-cli脚手架来搭建项目,配置过程会选择是否用到路由,如果选择y,后面下载依赖会自动下载vue-router
如果没有安装路由,name请看下面的指令
npm install vue-router
使用一个自定义组件 router-link 来创建链接。这使得 Vue Router 可以在不重新加载页面的情况下更改 URL,处理 URL 的生成以及编码。
to="/user"
举个栗子:

🐇 切换路由的地址
"{'name':'about'}">关于 - <router-link :to="{path:'/product/def',query:{age:18},hash:'best'}">产品router-link>
显示与 url 对应的组件。你可以把它放在任何地方,以适应你的布局。
- {
- path:"/user",
- name:"user",
- component:()=>import(xxx)
- }
第一步在router里配置
- {
- path:"/product/:id",
- name:"product",
- component:xxx
- }
第二步:在App.vue中链接
"/product/abc">
第三步: 在页面中获取
$route.params.id
- {
- path:"*"
- }
- 🐇 前进 forward()
- go(1)
- 🐇 后退 back()
- go(-1)
- 🐇 切换路由 push("/about")
- 🐇 替换路由(不留当前页面历史记录) replace("/about")
- 路由参数 params
- 查询 query
- 地址 path
- 全地址 fullPath
- 名称 name
- 哈希值 hash
组件内部
beforeRouterEnter(to,from,next)
to 要进入的路由
from 从哪个页面进入
next下一步
next(true) 进入to页面
next(false) 不跳转
next("/login") 跳转到登录
作用:进入离开页面前做拦截,处理事情(跳转提示,权限检查)
语法结构:
{path:path,name,component,
meta:{noFooter:true}
}
$route.meta.noFooter 范围
举个栗子:
- // 希望 cart页面 都需要登录才能进入
- // 在这些页面定义meta:{requireAuth:true}
- // 使用全局守卫(每个路由页面进入前都会执行 beforeEach的回调函数)
- router.beforeEach((to, from, next) => {
- if (to.meta.requireAuth) {
- // 如果需要权限,判断
- if (localStorage.getItem("token")) {
- // 如果有token
- next(true);
- } else {
- // 跳转到登录页面redirect
- next("/login?redirect=" + to.path)
- }
- } else {
- // 直接下一页
- next(true)
- }
- })