router基本配置
import Vue from "vue";
import VueRouter from "vue-router";
import A from "../components/A.vue";
import B from "../components/B.vue";
Vue.use(VueRouter);
const routes = [
{
path: "/a",
component: A,
},
{
path: "/b",
component: B,
},
];
export default new VueRouter({
routes,
});
基本写法
| <router-link active-class="" to=""></router-link> | router导航 |
| <router-view></router-view> | router展示 |
|
<keep-alive include=""> </keep-alive> | 保持活跃,组件不销毁(include可选) |
| replace | 替换历史记录(使页面不会后退) |
| push | 追加历史记录(默认) |
嵌套(多级)路由
| children | 配置嵌套(多级)路由 |
命名路由
| name | 给路由起名字,可以用此替代path路径 |
| meta | 路由元信息(自定义) |
query传参
|
:to="`/b/d/e?title=${i.title}`" | 基础写法(不建议) |
|
:to="{ path: '/b/d/e', query: { title: i.title, }, }" | 对象写法 |
|
$route.query.title |
- |
params传参
|
:to="`/b/d/e/${i.title}`" | 基础写法(不建议) |
|
:to="{ name: 'abc', params: { title: i.title, }, }" | 对象写法(必须使用name,不能使用path) |
| $route.params.title | - |
props传参
|
props:{} | 对象写法(不推荐,数据是固定的) |
|
props: true | 布尔值写法,若布尔值为真,就会把该路由组件收到的所有params参数以props的形式传给组件(只适用于params传参) |
|
props($router) { return { title: $router.params.title, }; } | 函数写法 |
生命周期
| activated | 路由组件被激活时 |
| activated | 路由组件失活时 |
导航守卫
|
router.beforeEach((to, from, next) => {}) | 全局前置路由守卫 |
|
router.beforeEach((to, from) => {}) | 全局后置路由守卫 |
|
beforeEnter: (to, from, next) => {} | 独享前置路由守卫(只有前置,没有后置) |
|
beforeRouteEnter(to, from, next) {} | 组件内进入守卫(通过路由规则进入该组件内时被调用) |
|
beforeRouteLeave(to, from, next) {} | 组件内离开守卫(通过路由规则离开该组件内时被调用) |
浏览器工作模式
| hash | hash模式 |
| history | history模式(项目上线后刷新页面会出现404) |
| mode | 设置浏览器工作模式 |
本文详细介绍了Vue Router的基本配置,包括路由实例化、路径映射、导航链接、守卫功能、工作模式选择等,适合初学者快速上手。
2679

被折叠的 条评论
为什么被折叠?



