搜索文档
安装
sh
npm i vue-router;配置文件
js
import { createWebHistory, createRouter } from 'vue-router'
const router = createRouter({
history: createWebHistory(),
routes: [
{ path: '/', redirect: '/home' },
{ path: '/home', component: () => import('../pages/Home') },
{ path: '/login', component: () => import('../pages/Login') },
{ path: '/:patchMath(.*)*', component: () => import('../pages/Error') }, // 404 页面
]
});
export default router;js
import { createApp } from 'vue';
import App from './App.vue';
import router from './router';
const app = createApp(App);
app.use(router);
app.mount('#app');编程式路由
vue
<template>
<h3 @click="jump">Home 组件</h3>
</template>
<script>
import { useRouter } from 'vue-router'
export default {
name: 'Vue3Home',
setup() {
const router = useRouter();
const jump = () => {
router.push('/login')
}
return { jump }
},
};
</script>注:push()、replace()、back()、forward()、go() 用法和 Vue2 一样
路由守卫
同 Vue2
路由的 props 配置项
对象写法:把对象中的每一组 key-value 作为 props 传给路由组件。
js
{
path: '/home',
component: () => import('../views/Home.vue'),
props: {a: 1, b: 2}
}布尔值写法:把收到了每一组 params 参数,作为 props 传给路由组件。
js
{
path: '/home/:a/:b',
component: () => import('../views/Home.vue'),
props: true
}函数写法:把函数返回值的对象中每一组 key-value 作为 props 传给路由组件。
js
{
path: '/home/:a/:b',
component: () => import('../views/Home.vue'),
props: (router) => {...router.query, ...router.params}
}