欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

vue3使用vue-router及路由權限攔截方式

 更新時間:2022年04月18日 08:56:51   作者:cookcyq  
這篇文章主要介紹了vue3使用vue-router及路由權限攔截方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教

使用vue-router及路由權限攔截

vue3 使用 vue-router 的方式和 vue2 基本一樣,只不過初始化路由時需要用到一些函數(shù)來定義而已,另外 vue-cli 工具本身在創(chuàng)建 vue3 項目時就可以根據(jù)提示來進行安裝配置 vue-router , 所以本篇只是針對那些忘記安裝的小伙伴。

第一步肯定是要先安裝啦:

npm install vue-router@4

接著我們在根目錄 src 下創(chuàng)建 router 目錄并定義 index.js

下面是 src/router/index.js 的代碼 

// 1. 引入這兩個函數(shù)來初始化路由
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. 創(chuàng)建路由實例
const router = createRouter({
  history: createWebHashHistory(), // 表示使用 hash 模式,即 url 會有 # 前綴
  routes
})
// 4. 你還可以監(jiān)聽路由攔截,比如權限驗證。
router.beforeEach((to, from, next) => {
  // 1. 每個條件執(zhí)行后都要跟上 next() 或 使用路由跳轉 api 否則頁面就會停留一動不動
  // 2. 要合理的搭配條件語句,避免出現(xiàn)路由死循環(huán)。
  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

至此就完成啦 

vue3使用vue-router講解

cnpm i vue-router@next -D

創(chuàng)建Router對象和路由配置——routerIndex.js

import {createRouter, createWebHashHistory, createWebHistory} from "vue-router"
// 1. 定義路由組件, 注意,這里一定要使用 文件的全名(包含文件后綴名)
import countIndex from "../pages/count/countIndex.vue";
import langshanIndex from "../pages/langshan/langshanIndex.vue";
// 2. 定義路由配置
const routes = [
  { 
    path: "/",
    redirect: '/countIndex'
  },
  { path: "/countIndex", component: countIndex },
  { path: "/langshanIndex", component: langshanIndex },
 
];
// 3. 創(chuàng)建路由實例
const router = createRouter({
  // 4. 采用hash 模式
  history: createWebHashHistory(),
  // 采用 history 模式
  // history: createWebHistory(),
  routes, //使用上方定義的路由配置
});
export default router 
//導出router

Router 當做插件引用進來——main.js

import { createApp } from 'vue'
import routerIndex from './router/routerIndex' ?// 引入路由對象實例
import App from './App.vue'
const app = createApp(App)
// 使用配置的路由
app.use(routerIndex)
app.mount('#app')

以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。 

相關文章

最新評論