まずvue-routerを使う必要がありますが、vue2とvue3では使い方も異なります
- まずvue-routerをインストールする必要があります
npm install vue-router@next -S
- 次に、プロジェクトのルート ディレクトリの src フォルダーの下に新しいルーター フォルダーを作成し、ルーター内に新しい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')
上記はvue3でのvue-routerの使用です。