1.下载 cnpm install vue-router -S ,本次下载的是 "vue-router": "^4.0.12"
2.创建 router/index.js
import {createRouter,createWebHashHistory} from 'vue-router'const Home = ()=>import("../page/home")const User = ()=>import("../page/user")const Role = ()=>import("../page/role")// 定义一些路由// 每个路由都需要映射到一个组件。const routes = [ { path: '/',name:"home", component: Home ,meta:{title:"首页"}}, { path: '/user',name:"use", component: User,meta:{title:"用户"} }, { path: '/role', name:"role",component: Role,meta:{title:"角色"} }, ]const router = createRouter({ // 在这里使用 hash **。 history: createWebHashHistory(), routes, // `routes: routes` 的缩写 }) // 全局前置守卫 router.beforeEach((to, from) => { document.title = to.meta.title || 'vue-demo'; // 设置title return true }) export default router
3. 在main.js中
import router from './router/index.js'const app = createApp(App)app.use(router)
4.app.vue文件
<template> <div class="header"> <h5><router-link to="/user">Go to user</router-link></h5> <h5><router-link to="/role">Go to role</router-link></h5> </div> <hr/> <div class="main"> <router-view></router-view> </div> </template><script> import { RouterView,RouterLink} from 'vue-router'export default { name: 'App', components: { RouterView, RouterLink }, setup(){ return { } }}</script><style></style>
5. 代码实现跳转
import {useRouter} from 'vue-router'; const router = new useRouter(); const go = ()=>{ router.push({ path: '/user', query: { id:1,username: 'hehe' }} ) }
6.参数获取
import {useRoute} from 'vue-router'; const route = new useRoute(); const getRouterParam = ()=>{ console.log(route.query) user.id = route.query.id user.username = route.query.username }