Home Web Front-end JS Tutorial Summary sharing of Vue routing hooks and application scenarios

Summary sharing of Vue routing hooks and application scenarios

Jan 19, 2018 pm 02:00 PM
Scenes application

This article mainly introduces the detailed explanation of Vue routing hooks and application scenarios (summary). The editor thinks it is quite good, so I will share it with you now and give it as a reference. Let’s follow the editor to take a look, I hope it can help everyone.

1. Routing hook syntax

In the official document of vue-router, routing hook is translated as navigation guard. The following is a summary of the content in the document. You can also send it by Go to the official website to read the details

Routing hook

The routing hook is mainly defined for users to perform some special processing when the route changes, rely on it. . What a mouthful.

Generally speaking, Vue provides three major types of hooks

1, global hooks
2, hooks exclusive to a certain route
3, In-component hooks

All three routing hooks involve three parameters. Let’s go directly to the official introduction here

to: Route: The target routing object that is about to enter
from: Route: The route that the current navigation is about to leave
next: Function: This method must be called to resolve this hook. The execution effect depends on the calling parameters of the next method.
next(): Proceed to the next hook in the pipeline. If all hooks are executed, the navigation status is confirmed.
next(false): Interrupt current navigation. If the browser's URL changes (perhaps manually by the user or by the browser's back button), the URL address will be reset to the address corresponding to the from route.
next(‘/’) or next({ path: ‘/’ }): Jump to a different address. The current navigation is interrupted and a new navigation is started.

(1). Global guard (global routing hook)

You can use router.beforeEach to register a global pre-guard:

const router = new VueRouter({ ... })

router.beforeEach((to, from, next) => {
 // ...
 next()
})
Copy after login

Each guard method accepts three Parameters:

  1. to: Route: The target route object that is about to enter

  2. from: Route: The route that the current navigation is about to leave

  3. next: Function: This method must be called to resolve this hook. The execution effect depends on the calling parameters of the next method

Note: When using the global routing hook, be sure to call next()!!!

(2). Exclusive to routing Guards (in-route hooks)

You can directly define beforeEnter guards in the routing configuration:

const router = new VueRouter({
 routes: [
  {
   path: '/foo',
   component: Foo,
   beforeEnter: (to, from, next) => {
    // ...
   }
  }
 ]
})
Copy after login

The method parameters of these guards are the same as those of global front guards.

(3). Guards within the component (hook within the component)

Finally, you can directly define the routing navigation guard in the routing component:

  1. beforeRouteEnter

  2. beforeRouteUpdate (new in 2.2)

  3. beforeRouteLeave

const Foo = {
 template: `...`,
 beforeRouteEnter (to, from, next) {
  // 在渲染该组件的对应路由被 confirm 前调用
  // 不!能!获取组件实例 `this`
  // 因为当守卫执行前,组件实例还没被创建
 },
 beforeRouteUpdate (to, from, next) {
  // 在当前路由改变,但是该组件被复用时调用
  // 举例来说,对于一个带有动态参数的路径 /foo/:id,在 /foo/1 和 /foo/2 之间跳转的时候,
  // 由于会渲染同样的 Foo 组件,因此组件实例会被复用。而这个钩子就会在这个情况下被调用。
  // 可以访问组件实例 `this`
 },
 beforeRouteLeave (to, from, next) {
  // 导航离开该组件的对应路由时调用
  // 可以访问组件实例 `this`
 }
}
Copy after login

2. Routing Application scenarios of hooks in actual development

Routing hooks are rarely used in the actual development process. In actual projects, I have only used beforeRouteLeave within components. The usage scenarios are as follows:

(1) Clear the timer in the current component

When there is a timer in a component, when the route is switched, you can use beforeRouteLeave to clear the timer to avoid occupying memory. :

beforeRouteLeave (to, from, next) {
 window.clearInterval(this.timer) //清楚定时器
 next()
}
Copy after login

(2) When there are unclosed windows or unsaved content on the page, prevent the page from jumping

If there is important information in the page that requires the user to save it before proceeding Jump, or there is a pop-up box. Users should be prevented from jumping

 beforeRouteLeave (to, from, next) {
 //判断是否弹出框的状态和保存信息与否
 if (this.dialogVisibility === true) {
  this.dialogVisibility = false //关闭弹出框
  next(false) //回到当前页面, 阻止页面跳转
 }else if(this.saveMessage === false) {
  alert('请保存信息后退出!') //弹出警告
  next(false) //回到当前页面, 阻止页面跳转
 }else {
  next() //否则允许跳转
 }
}
Copy after login

(3) Save relevant content to Vuex or Session

When the user needs to close the page, the public The information is saved in session or Vuex

 beforeRouteLeave (to, from, next) {
  localStorage.setItem(name, content); //保存到localStorage中
  next()
}
Copy after login

Related recommendations:

Judge whether the user is logged in when the vue route jumps

Detailed explanation of Vue routing nested SPA implementation steps

An example tutorial that summarizes Vue routing jump issues

The above is the detailed content of Summary sharing of Vue routing hooks and application scenarios. 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
3 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 solve the long tail problem in autonomous driving scenarios? How to solve the long tail problem in autonomous driving scenarios? Jun 02, 2024 pm 02:44 PM

Yesterday during the interview, I was asked whether I had done any long-tail related questions, so I thought I would give a brief summary. The long-tail problem of autonomous driving refers to edge cases in autonomous vehicles, that is, possible scenarios with a low probability of occurrence. The perceived long-tail problem is one of the main reasons currently limiting the operational design domain of single-vehicle intelligent autonomous vehicles. The underlying architecture and most technical issues of autonomous driving have been solved, and the remaining 5% of long-tail problems have gradually become the key to restricting the development of autonomous driving. These problems include a variety of fragmented scenarios, extreme situations, and unpredictable human behavior. The "long tail" of edge scenarios in autonomous driving refers to edge cases in autonomous vehicles (AVs). Edge cases are possible scenarios with a low probability of occurrence. these rare events

The role and practical application of arrow symbols in PHP The role and practical application of arrow symbols in PHP Mar 22, 2024 am 11:30 AM

The role and practical application of arrow symbols in PHP In PHP, the arrow symbol (->) is usually used to access the properties and methods of objects. Objects are one of the basic concepts of object-oriented programming (OOP) in PHP. In actual development, arrow symbols play an important role in operating objects. This article will introduce the role and practical application of arrow symbols, and provide specific code examples to help readers better understand. 1. The role of the arrow symbol to access the properties of an object. The arrow symbol can be used to access the properties of an object. When we instantiate a pair

How to Undo Delete from Home Screen in iPhone How to Undo Delete from Home Screen in iPhone Apr 17, 2024 pm 07:37 PM

Deleted something important from your home screen and trying to get it back? You can put app icons back on the screen in a variety of ways. We have discussed all the methods you can follow and put the app icon back on the home screen. How to Undo Remove from Home Screen in iPhone As we mentioned before, there are several ways to restore this change on iPhone. Method 1 – Replace App Icon in App Library You can place an app icon on your home screen directly from the App Library. Step 1 – Swipe sideways to find all apps in the app library. Step 2 – Find the app icon you deleted earlier. Step 3 – Simply drag the app icon from the main library to the correct location on the home screen. This is the application diagram

From beginner to proficient: Explore various application scenarios of Linux tee command From beginner to proficient: Explore various application scenarios of Linux tee command Mar 20, 2024 am 10:00 AM

The Linuxtee command is a very useful command line tool that can write output to a file or send output to another command without affecting existing output. In this article, we will explore in depth the various application scenarios of the Linuxtee command, from entry to proficiency. 1. Basic usage First, let’s take a look at the basic usage of the tee command. The syntax of tee command is as follows: tee[OPTION]...[FILE]...This command will read data from standard input and save the data to

Explore the advantages and application scenarios of Go language Explore the advantages and application scenarios of Go language Mar 27, 2024 pm 03:48 PM

The Go language is an open source programming language developed by Google and first released in 2007. It is designed to be a simple, easy-to-learn, efficient, and highly concurrency language, and is favored by more and more developers. This article will explore the advantages of Go language, introduce some application scenarios suitable for Go language, and give specific code examples. Advantages: Strong concurrency: Go language has built-in support for lightweight threads-goroutine, which can easily implement concurrent programming. Goroutin can be started by using the go keyword

Have you used these stress testing tools for Linux systems? Have you used these stress testing tools for Linux systems? Mar 21, 2024 pm 04:12 PM

As an operation and maintenance personnel, have you ever encountered this scenario? You need to use tools to test high system CPU or memory usage to trigger alarms, or test the concurrency capabilities of the service through stress testing. As an operation and maintenance engineer, you can also use these commands to reproduce fault scenarios. Then this article can help you master commonly used testing commands and tools. 1. Introduction In some cases, in order to locate and reproduce problems in the project, tools must be used to conduct systematic stress testing to simulate and restore fault scenarios. At this time testing or stress testing tools become particularly important. Next, we will explore the use of these tools according to different scenarios. 2. Test Tools 2.1 Network speed limiting tool tctc is a command line tool used to adjust network parameters in Linux. It can be used to simulate various networks.

The wide application of Linux in the field of cloud computing The wide application of Linux in the field of cloud computing Mar 20, 2024 pm 04:51 PM

The wide application of Linux in the field of cloud computing With the continuous development and popularization of cloud computing technology, Linux, as an open source operating system, plays an important role in the field of cloud computing. Due to its stability, security and flexibility, Linux systems are widely used in various cloud computing platforms and services, providing a solid foundation for the development of cloud computing technology. This article will introduce the wide range of applications of Linux in the field of cloud computing and give specific code examples. 1. Application virtualization technology of Linux in cloud computing platform Virtualization technology

Let's talk about the model fusion method of large models Let's talk about the model fusion method of large models Mar 11, 2024 pm 01:10 PM

In previous practices, model fusion has been widely used, especially in discriminant models, where it is considered a method that can steadily improve performance. However, for generative language models, the way they operate is not as straightforward as for discriminative models because of the decoding process involved. In addition, due to the increase in the number of parameters of large models, in scenarios with larger parameter scales, the methods that can be considered by simple ensemble learning are more limited than low-parameter machine learning, such as classic stacking, boosting and other methods, because stacking models The parameter problem cannot be easily expanded. Therefore, ensemble learning for large models requires careful consideration. Below we explain five basic integration methods, namely model integration, probabilistic integration, grafting learning, crowdsourcing voting, and MOE

See all articles