Vue.js 路由允许我们通过不同的 URL 访问不同的内容。
通过 Vue.js 可以实现多视图的单页Web应用(single page web application,SPA)。
1、普通路由配置
- {
- path: '/user', //配置的路径
- name: 'user', //名称
- component: () => import('xxx)
- }
- {
- path:“/product/:id”,
-
- name:"product",
-
- component:xxx
-
- }
-
-
"/product/abc"> - 在页面中获取:$route.params.id
- }
三、404页面
-
- <div>
- <h1>404h1>
- <p>您的页面被外星人绑架了!p>
- <router-link to="/">回首页router-link>
- div>
-
- // 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'