Home Web Front-end Vue.js How to use routing to dynamically control page permissions in Vue?

How to use routing to dynamically control page permissions in Vue?

Jul 21, 2023 pm 07:09 PM
- vue - Routing - Page permissions

How to use routing to achieve dynamic control of page permissions in Vue?

When using Vue to develop front-end applications, it is often necessary to control page permissions, that is, some pages can only be accessed by specific users. In order to achieve dynamic control of page permissions, we can use the routing function in Vue for processing.

1. Create a routing configuration file

First, create a new file in the routing folder of the project and name it router.js. In this file, we can edit the routing configuration information. The following is an example routing configuration file:

import Vue from 'vue';
import Router from 'vue-router';

// 引入需要进行权限控制的页面组件
import HomePage from '../components/HomePage.vue';
import AdminPage from '../components/AdminPage.vue';
import UserPage from '../components/UserPage.vue';

Vue.use(Router);

const router = new Router({
  routes: [
    // 首页
    {
      path: '/',
      name: 'HomePage',
      component: HomePage,
      meta: {
        requiresAuth: true // 需要权限验证
      }
    },
    // 管理员页面
    {
      path: '/admin',
      name: 'AdminPage',
      component: AdminPage,
      meta: {
        requiresAuth: true, // 需要权限验证
        role: 'admin' // 需要角色为admin
      }
    },
    // 普通用户页面
    {
      path: '/user',
      name: 'UserPage',
      component: UserPage,
      meta: {
        requiresAuth: true, // 需要权限验证
        role: 'user' // 需要角色为user
      }
    },
  ]
});

export default router;
Copy after login

In this configuration file, we first introduce Vue and router, and use Vue's use method to register the routing plug-in. Then, we defined three routes, namely the home page, the administrator page and the ordinary user page. Their access paths are '/', '/admin' and '/user' respectively. Each route has a meta field, which contains the permission information required by the route. Among them, the requiresAuth field indicates whether the route requires permission verification, and the role field indicates the role required by the route.

2. Set the global navigation guard

Next, we need to set the global navigation guard in the Vue entry file for permission verification when routing. The following is an example entry file:

import Vue from 'vue';
import App from './App.vue';
import router from './router';

Vue.config.productionTip = false;

// 设置全局导航守卫
router.beforeEach((to, from, next) => {
  // 检查该路由是否需要进行权限验证
  if (to.meta.requiresAuth) {
    const role = localStorage.getItem('role'); // 获取当前用户的角色信息
    // 检查用户的角色是否满足路由所需的角色
    if (!role || to.meta.role !== role) {
      // 如果用户的角色不满足路由所需的角色,则跳转到登录页面或无权限页面
      next('/login'); // 跳转到登录页面
    } else {
      next(); // 跳转到该路由
    }
  } else {
    next(); // 跳转到该路由
  }
});

new Vue({
  router,
  render: (h) => h(App),
}).$mount('#app');
Copy after login

In this entry file, we first introduced Vue, App component and router, and created a Vue instance. Then, we set a global navigation guard through the router.beforeEach method. In the navigation guard, we first check whether the route requires permission verification. If verification is required, obtain the role information of the current user. Then, we check whether the user's role meets the role required by the route. If not, we perform corresponding processing, such as jumping to the login page or no permission page. If the user's role meets the role required by the route, jump to the route. Finally, we create a Vue instance and pass the router into it.

3. Use routing to control page permissions

Now, we can use routing in the component to control page permissions. The following is an example component:

<template>
  <div>
    <!-- 编写组件内容 -->
  </div>
</template>

<script>
export default {
  name: 'HomePage',
  mounted() {
    // 页面加载时自动跳转到登录页面
    this.$router.push('/login');
  },
};
</script>
Copy after login

In the example component, we use the this.$router.push method to implement routing jump. When the page loads, we automatically jump to the login page. Of course, you can also use other routing methods according to specific needs, such as this.$router.replace or this.$router.go, etc.

Through the above steps, we successfully implemented dynamic control of page permissions based on routing. Users can access the corresponding page only if they meet the role conditions required for routing. In this way, we can effectively protect the security of sensitive pages and ensure that only authorized users can access them.

The above is the detailed content of How to use routing to dynamically control page permissions in Vue?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use v-on:click.once in Vue to realize that the event is only triggered once How to use v-on:click.once in Vue to realize that the event is only triggered once Jun 11, 2023 pm 12:52 PM

Vue is a popular JavaScript framework that provides rich instructions to implement interactive user interfaces. Among them, the event processing instruction v-on can be added to the label to bind an event processing function. However, sometimes we want a button to be clicked only once, instead of triggering the corresponding event handler every time it is clicked. So how to use v-on:click.once in Vue to realize that the event is only triggered once? How to use v-on:click.once in Vue

Getting Started with VUE3: Using provide/inject to share between components Getting Started with VUE3: Using provide/inject to share between components Jun 16, 2023 am 08:34 AM

VUE is a modern front-end framework with the advantages of high ease of use, strong flexibility, and excellent performance. It is increasingly popular and favored by front-end developers. The VUE3 version brings better performance, better architectural design, and is more user-friendly. VUE3 provides a new way to realize the function of sharing data between components - provide/inject. This article will introduce the usage and implementation process of provide/inject in detail. Overviewprovide/

Tips and best practices for using single-file components to implement component modularization in Vue Tips and best practices for using single-file components to implement component modularization in Vue Jun 25, 2023 am 08:12 AM

Vue is a popular JavaScript framework that is widely used to develop single-page applications and dynamic websites. Among them, componentization and modularization are one of its core features. Vue uses Single-File Components (SFC) to implement modularization of components and improve the efficiency of writing, maintaining and testing components. This article will introduce tips and best practices for using single-file components to modularize Vue components. What is a single file component? Single file component refers to

Detailed explanation of Vue instructions: v-model, v-if, v-for, etc. Detailed explanation of Vue instructions: v-model, v-if, v-for, etc. Jun 09, 2023 pm 04:06 PM

With the continuous development of front-end technology, front-end framework has become an important part of modern web application development. Among them, Vue.js, as an excellent and lightweight MVVM framework, is favored by front-end developers. The Vue.js command is a very important functional module in the Vue.js framework. Among them, v-model, v-if, v-for and other commands are indispensable tools for developing Vue.js applications. Below we will analyze the usage and function of these instructions in detail. 1. v-mo

How Vue implements file upload function How Vue implements file upload function Feb 19, 2024 pm 06:23 PM

How to implement vue's Upload function. With the development of web applications, the file upload function has become more and more common. Vue is a popular JavaScript framework that provides a convenient way to build modern web applications. In Vue, you can implement the file upload function by using Vue's Upload component. This article will introduce how to use Vue to implement the file upload function and provide specific code examples. First, install the required dependencies in the Vue project. You can use n

Vue and Vue-Router: How to use routing information in components? Vue and Vue-Router: How to use routing information in components? Dec 17, 2023 pm 01:46 PM

Vue and Vue-Router: How to use routing information in components? Introduction: During the development process of Vue.js, it is often necessary to obtain and use routing information in components, such as obtaining current URL parameters, jumping between different pages, etc. Vue.js provides the Vue-Router plug-in to implement front-end routing functions. This article will introduce how to use Vue-Router in components to obtain and utilize routing information. Introduction to Vue-Router: Vue-Router is Vue

How to use Vue to implement tag cloud effects How to use Vue to implement tag cloud effects Sep 20, 2023 pm 03:21 PM

How to use Vue to implement tag cloud effects Introduction: Tag cloud is a common web page effect that displays tags with different font sizes to show the popularity or relevance of tags. In this article, we will introduce how to use the Vue framework to implement tag cloud effects and provide specific code examples. Step 1: Build a Vue project First, we need to build a basic Vue project. You can use VueCLI to quickly generate a project skeleton. Open the command line tool and enter the following command: vuecreate

nextTick function in Vue3: processing operations after DOM update nextTick function in Vue3: processing operations after DOM update Jun 18, 2023 am 10:06 AM

Vue3 is a very popular front-end framework recently. Its biggest feature is virtual DOM technology, that is, Vue will convert the real DOM tree into a virtual DOM tree, and then convert it into a real DOM tree after operating on the virtual DOM tree. DOM tree. This technology allows us to operate DOM more efficiently, and can also achieve very good performance when the number of DOM is large. However, due to the particularity of virtual DOM technology, when we operate DOM, sometimes we cannot get the latest DO immediately.

See all articles