首先需要使用vue-router在vue2和vue3的用法也是存在差别的
- 首先你需要安装vue-router
npm install vue-router@next -S
- 然后再项目的根目录下面src文件夹下面新建router这个文件夹, router中新建index.js这个文件
import { createRouter, createWebHashHistory } from 'vue-router'
const routes = [
// 路由重定向
{
path: '/',
redirect: '/home'
},
{
path: '/home',
name: 'home',
// 路由懒加载
component: () => import('../views/home.vue'),
meta: {
name: 'why',
age: 20,
height: 1.88
},
children: [
{
path: 'message',
component: () => import('../components/message.vue')
},
{
path: 'production',
component: () => import('../components/production.vue')
}
]
},
{
path: '/about',
component: () => import('../views/about.vue')
},
{
path: '/user/:username/id/:id',
component: () => import('../views/User.vue'),
name: 'username',
meta: {
name: 'username'
}
},
{
path: '/login',
component: () => import('../components/Login.vue')
},
{
path: '/:pathMatch(.*)',
component: () => import('../views/NotFound.vue')
}
]
const router = createRouter({
routes,
history: createWebHashHistory(),
linkActiveClass: 'why-active',
linkExactActiveClass: 'why-exact-active'
})
// 动态添加路由
const Category = {
path: '/category',
component: () => import('../components/Category.vue')
}
// 动态添加顶级路由
router.addRoute(Category)
// 动态添加二级路由
const moment = {
path: 'moment',
component: () => import('../components/moment.vue')
}
router.addRoute('home', moment)
let count = 0
// to: 表示跳转的路由对象, from表示从哪里跳过来的
router.beforeEach((to, from) => {
console.warn(to, from)
// eslint-disable-next-line no-template-curly-in-string
console.log(`路由跳转${++count}`)
// if (to.path.indexOf('home') !== -1) {
// return '/login'
// }
if (to.path !== 'login') {
// return '/login'
const token = window.localStorage.getItem('key')
if (!token) return '/login'
}
// return false
})
export default router
在入口文件main.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-router在vue3中的使用