×

vue3应用:vue-router及路由权限拦截方式

作者:Terry2022.06.24来源:Web前端之家浏览:6915评论:0
关键词:vuejs

vue3应用:vue-router及路由权限拦截方式。

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

至此就完成啦 

vue3使用vue-router讲解

cnpm i vue-router@next -D

创建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. 创建路由实例
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')

您的支持是我们创作的动力!
温馨提示:本文作者系Terry ,经Web前端之家编辑修改或补充,转载请注明出处和本文链接:
https://jiangweishan.com/article/vuejs20220624a1.html

网友评论文明上网理性发言 已有0人参与

发表评论: