vue3 使用 vue-router 的方式和 vue2 基本一樣,只不過初始化路由時需要用到一些函式來定義而已,另外 vue-cli 工具本身在創建 vue3 專案時就可以根據提示來進行安裝配置 vue-router , 所以本篇只是針對那些忘記安裝的小伙伴,
第一步肯定是要先安裝啦:npm install vue-router@4
接著我們在根目錄 src 下創建 router 目錄并定義 index.js
下面是 src/router/index.js 的代碼
// 1. 引入這兩個函式來初始化路由
import { createRouter, createWebHashHistory } from "vue-router"
// 2. 配置路由
const routes = [
{
path: '/info',
name: 'info',
component: () => import('@/pages/info'),
// 路由元資訊,隨你怎么定義,筆者一般采用這種方式來定義路由權限然后結合路由攔截,
// 下面的 auth:true 表示需要授權登錄才可以進入此頁面,
meta: {
auth: true,
},
},
{
path: '/login',
name: 'login',
component: () => import('@/pages/login'),
meta: {
auth: false,
},
}
]
// 3. 創建路由實體
const router = createRouter({
history: createWebHashHistory(), // 表示使用 hash 模式,即 url 會有 # 前綴
routes
})
// 4. 你還可以監聽路由攔截,比如權限驗證,
router.beforeEach((to, from, next) => {
// 1. 每個條件執行后都要跟上 next() 或 使用路由跳轉 api 否則頁面就會停留一動不動
// 2. 要合理的搭配條件陳述句,避免出現路由死回圈,
const token = cookies.get('token')
if (to.meta.auth) {
if (!token) {
return router.replace({
name: 'login'
})
}
next()
} else {
next()
}
})
export default router
接下來在專案的入口檔案 main.js 里面引入 router/index.js
// main.js
import { createApp } from 'vue'
import router from '@/router/index.js' // 引入
import App from '@/App.vue'
const app = createApp(App)
app
.use(router)
.mount('#app')
export default app
至此就完成啦
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/374790.html
標籤:其他
上一篇:react最新筆記
