Home Web Front-end Vue.js Use redirection to implement dynamic route switching in Vue Router

Use redirection to implement dynamic route switching in Vue Router

Sep 15, 2023 pm 03:18 PM
dynamic routing Redirect vue router

在 Vue Router 中使用重定向实现动态路由切换

Using redirection in Vue Router to implement dynamic routing switching requires specific code examples

When using Vue.js to develop a single-page application, Vue Router is a Very powerful and flexible routing library. Vue Router allows us to map different URLs to different view components by configuring routing tables. In addition to basic route mapping, Vue Router also supports redirection functionality, which means that a route can be redirected to another route.

In some cases, we may need to implement dynamic routing switching based on specific logical requirements. For example, routing switching is performed based on the user's role. If it is an administrator role, it will jump to the management page; if it is an ordinary user role, it will jump to the ordinary user page.

The following is an example that demonstrates how to use the redirection function of Vue Router to implement dynamic routing switching:

First, you need to install and introduce Vue Router into the project. You can install Vue Router through npm or yarn, and then introduce and use it in the project entry file:

// 安装 Vue Router,执行命令:
// npm install vue-router 或 yarn add vue-router

// 入口文件 main.js 中引入和使用 Vue Router
import Vue from 'vue'
import VueRouter from 'vue-router'

// 引入组件
import Admin from './components/Admin.vue'
import User from './components/User.vue'
import NotFound from './components/NotFound.vue'

// 使用 Vue Router
Vue.use(VueRouter)

// 定义路由表
const routes = [
  {
    path: '/admin',
    component: Admin,
    meta: { requiresAdmin: true },
  },
  {
    path: '/user',
    component: User,
    meta: { requiresAdmin: false },
  },
  {
    path: '/not-found',
    component: NotFound,
    meta: { requiresAdmin: false },
  },
  {
    path: '*',
    redirect: '/not-found',
  },
]

// 创建路由实例
const router = new VueRouter({
  mode: 'history',
  routes,
})

// 在路由切换前进行验证
router.beforeEach((to, from, next) => {
  const requiresAdmin = to.meta.requiresAdmin || false

  // 根据用户角色进行重定向
  if (requiresAdmin) {
    const isAdmin = // 假设通过某个函数判断用户是否为管理员
    if (isAdmin) {
      next()
    } else {
      next('/user')
    }
  } else {
    next()
  }
})

// 实例化 Vue
new Vue({
  router,
}).$mount('#app')
Copy after login

In the above code, we defined two routes, one is /admin, The other one is /user. At the same time, we also define a meta-information named requiresAdmin, which is used to identify whether the route requires administrator permissions. Based on this information, we implemented the redirection logic for the route in the beforeEach navigation guard.

In the navigation guard, we first obtain the requiresAdmin meta-information of the target route and determine whether the user has administrator rights. If the user is an administrator, jump to the /admin route, otherwise jump to the /user route. This enables the function of dynamically switching routes based on user roles.

If the user accesses a route that does not exist, we also provide a generic 404 page to redirect them to the /not-found route.

Through the above example, we can see that it is not difficult to implement dynamic route switching using the Vue Router redirection function. We only need to define the path to be redirected in the routing table, and determine the redirection target path based on specific logic in the navigation guard. In this way, we can dynamically switch routes according to different needs and provide a better user experience.

The above is the detailed content of Use redirection to implement dynamic route switching in Vue Router. 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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

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)

Understand common application scenarios of web page redirection and understand the HTTP 301 status code Understand common application scenarios of web page redirection and understand the HTTP 301 status code Feb 18, 2024 pm 08:41 PM

Understand the meaning of HTTP 301 status code: common application scenarios of web page redirection. With the rapid development of the Internet, people's requirements for web page interaction are becoming higher and higher. In the field of web design, web page redirection is a common and important technology, implemented through the HTTP 301 status code. This article will explore the meaning of HTTP 301 status code and common application scenarios in web page redirection. HTTP301 status code refers to permanent redirect (PermanentRedirect). When the server receives the client's

Redirect tutorial in PHP Redirect tutorial in PHP Sep 01, 2023 pm 05:53 PM

Redirects allow you to redirect client browsers to different URLs. You can use it when switching domains, changing website structure, or switching to HTTPS. In this article, I will show you how to redirect to another page using PHP. I'll explain exactly how PHP redirects work and show you what's happening behind the scenes. Learn PHP with Free Online Courses If you want to learn PHP, check out our PHP Basics free online course! PHP Basics Jeremy McPeak October 29, 2021 How do basic redirects work? Before we get into the details of PHP redirection, let’s take a quick look at how HTTP redirection actually works. Take a look at the image below. Let us understand the above screen

How to select the routing mode in Vue Router? How to select the routing mode in Vue Router? Jul 21, 2023 am 11:43 AM

VueRouter is the routing manager officially provided by Vue.js. It can help us implement page navigation and routing functions in Vue applications. When using VueRouter, we can choose different routing modes according to actual needs. VueRouter provides three routing modes, namely hash mode, history mode and abstract mode. The following will introduce in detail the characteristics of these three routing modes and how to choose the appropriate routing mode. Hash mode (default

How to use Vue Router for routing jump in uniapp How to use Vue Router for routing jump in uniapp Oct 18, 2023 am 08:52 AM

How to use VueRouter for routing jumps in uniapp Using VueRouter for routing jumps in uniapp is a very common operation. This article will introduce in detail how to use VueRouter in the uniapp project and provide specific code examples. 1. Install VueRouter Before using VueRouter, we need to install it first. Open the command line, enter the root directory of the uniapp project, and then execute the following command to install

PHP domain name redirection example demonstration and effect display PHP domain name redirection example demonstration and effect display Mar 28, 2024 am 08:21 AM

PHP domain name redirection is one of the commonly used technologies in website development. Through domain name redirection, users can automatically jump to another URL when visiting one URL, thereby achieving website traffic guidance, brand promotion and other purposes. The following will use a specific example to demonstrate the implementation method of PHP domain name redirection and show the effect. Create a simple PHP file named redirect.php with the following code:

How to use named routes in Vue Router? How to use named routes in Vue Router? Jul 23, 2023 pm 05:49 PM

How to use named routes in VueRouter? In Vue.js, VueRouter is an officially provided routing manager that can be used to build single-page applications. VueRouter allows developers to define routes and map them to specific components to control jumps and navigation between pages. Named routing is one of the very useful features. It allows us to specify a name in the routing definition, and then jump to the corresponding route through the name, making the routing jump more convenient.

Interpreting HTTP Status Code 302: A Deep Dive into Redirects and Temporary Jumps Interpreting HTTP Status Code 302: A Deep Dive into Redirects and Temporary Jumps Dec 26, 2023 am 08:09 AM

HTTP status code is a kind of status information returned by the web server to the browser. It is expressed in the form of three digits. Among them, status code 302 represents redirection, also known as temporary jump. This article will deeply analyze HTTP status code 302 and discuss its principles and applications. 1. Overview Redirection is an important concept in the HTTP protocol. When the browser sends a request to the server, the server may return a redirection status code to notify the browser that the current request needs to be redirected, that is, the requested resource address is transferred to another location.

How to use Vue Router to achieve transition effect when switching routes? How to use Vue Router to achieve transition effect when switching routes? Jul 21, 2023 pm 06:55 PM

How to use VueRouter to achieve transition effect when routing switching? Introduction: VueRouter is a routing management library officially recommended by Vue.js for building SPA (SinglePageApplication). It can achieve switching between pages by managing the correspondence between URL routing and components. In actual development, in order to improve user experience or meet design needs, we often use transition effects to add dynamics and beauty to page switching. This article will introduce how to use

See all articles