Article directory
overview
backend routing
1. According to different user URL requests, different content is returned, which is essentially the correspondence between URL request addresses and server resources.
2. However, there are performance problems in back-end rendering.
front-end routing
3. So there is Ajax pre-editing rendering. Front-end rendering can improve performance, but it does not support the browser's forward and backward operations.
4. At this time, SPA (Single Page Application) single-page application program appeared again. The entire website has only one page. The change of content is realized through Ajax partial update, and it supports the forward and backward operations of the browser address bar.
5. One of the SPA implementation principles is based on the hash of the URL address (the change of the hash will cause the browser to record the change of the access history, but the change of the hash will not trigger a new URL request). In the process of implementing SPA, the core technical point is front-end routing.
6. Front-end routing is to display different page content according to different user events. The essence is the correspondence between user events and event processing functions.
Router View
Here is the official documentation link
Vue Router is the official routing manager for Vue.js. It is deeply integrated with the core of Vue.js and can be very conveniently used for the development of SPA applications.
It functions as follows:
1. Support HTML5 history mode or hash mode.
2. Support nested routing.
3. Support routing parameters.
4. Support programmatic routing.
5. Support named routing.
Install
npm install vue-router --save
Common usage of vue-router
Routing lazy loading
The way of lazy loading of routes
Method 1: Combining Vue's asynchronous components and Webpack's code analysis
const Home = resolve => {
require. ensure(['../ components/Home.vue'], () => {
resolve(require('../ components/Home.vue')) })};
Method 2: AMD writing method
const About = resolve => require([' ../ components/ About.vue'], resolve);
Method 3: In ES6, we can have a simpler way to organize the code splitting of Vue asynchronous components and Webpack
const Home = () => import(' . ./ components/Home.vue ' )
The effect of lazy loading of routes:
route redirection
Routing redirection refers to: when a user accesses address A, the user is forced to jump to address C to display a specific component page.
By specifying a new routing address through the redirect attribute of the routing rule, you can easily set the routing redirection:
when the hash is /, it will jump to the home component by default, preventing nothing from being displayed when the hash is /, and the scene is just entered page, the home page is displayed by default
{ path: '*', component: NotFound } can be added at the end, indicating that this component will be displayed when none of the above routes match
nested routes
The nested display of components through routing is called nested routing.
For example, there are two subcomponents that need to be displayed in the about component
Declare subroute links and subroute placeholders
In the About.vue component, declare the child route links for tab1 and tab2 and the child route placeholders. The sample code is as follows:
Declare sub-routing rules through the children attribute
In the src/router/index.js routing module, import the required components, and use the children attribute to declare sub-routing rules:
Note: the path of the sub-routing does not need to add /
dynamic route matching
Thinking: There are three routing links as follows:
After the movie is the parameter, and the corresponding data will be rendered to the Movie component according to the parameter
Is it feasible to define the following three routing rules?
Disadvantage: The reusability of routing rules is poor.
The concept of dynamic routing
Dynamic routing refers to defining the variable part of the Hash address as a parameter item, thereby improving the reusability of routing rules.
Use the English colon (:) in vue-router to define the parameter items of the route. The sample code is as follows:
In this case, /movie/:id must pass parameters, and /movie/:id? means that no parameters can be passed
$route.params parameter object
In the component rendered by the dynamic route, you can use the this.$route.params object to access the dynamically matched parameter value, and you do not need to add this in the template.
Use props to receive route parameters
In order to simplify the acquisition form of routing parameters, vue-router allows to enable props parameter passing in routing rules. The sample code is as follows:
Declarative Navigation & Programmatic Navigation
Declarative Navigation
In the browser, clicking on the link to achieve navigation is called declarative navigation . For example:
- Clicking
<a>
links in ordinary web pages and clicking in Vue projects<router-link>
are all declarative navigation
In the browser, the method of calling API methods to realize navigation is called programmatic navigation . For example:
- The method of calling location.href to jump to a new page in a normal web page belongs to programmatic navigation
programmatic navigation
router.push
jumps to the specified hash address and adds a history record
Call this.$router.push() method to jump to the specified hash address and display the corresponding component page. The sample code is as follows:
router.replace
jumps to the specified hash address and replaces the current history record
Similar to push, the difference:
- push will add a history record
- replace does not add to the history, but replaces the current history
router.go
implements navigation history forward and backward
Call this.$router.go() method to move forward and backward in the browsing history. The sample code is as follows:
Simplification: In actual development, generally only one layer of pages will be moved forward and backward. Therefore, vue-router provides the following two convenient methods:
$router.back()
In history, go back to the previous page
$router.forward()
In history, advance to the next page
navigation guard
Navigation guards can control access to routes. The schematic diagram is as follows:
Global Front Guard
Every time a routing navigation jump occurs, the global pre-guard will be triggered. Therefore, in the global pre-guard, programmers can control the access rights of each route:
The 3 formal parameters of the guard method
The callback function of the global pre-guard receives 3 formal parameters in the format:
3 ways to call the next function
Referring to the schematic diagram, analyze the final results of the three calling methods of the next function:
The current user has the access right to the background home page, and can be released directly: next()
The current user does not have access to the background home page, forcing it to jump to the login page: next('/login')
The current user does not have access to the background homepage, and jumping to the background homepage is not allowed: next(false)
Control access to the background home page
When many navigation guards are required, the following approach can be used:
// 全局前置守卫
router.beforeEach((to, from, next) => {
// 要进行导航守卫的路径值
const pathArr = ['/home','/home/users', '/home/rights']
if (pathArr.indexOf(to.path) !== -1) {
const token = localStorage.getItem('token')
if (token) {
next()
} else {
next('/login')
}
} else {
next()
}
})
Another way of writing is to add a meta configuration item to each route, and judge whether it needs to be judged by the true and false values in the meta
{
path: 'users',
component: Users,
meta: {
isAuth: true },
},
...
// 全局前置守卫
router.beforeEach((to, from, next) => {
if (to.meta.isAuth) {
// 判断是否需要进行导航守卫
const token = localStorage.getItem('token')
if (token) {
next()
} else {
next('/login')
}
} else {
next()
}
})
Two working modes of routing
hash mode
- By default, the working mode of hash is enabled.
#
It means hash, followed by the hash value- Note: the values after # are not sent to the server
history mode
To enable the history mode, you need to add a mode configuration item. The default is hash
history without #
The difference between hash and history
hsah mode
- There is always a # sign in the address, which is not beautiful
- If the address is shared through a third-party mobile app in the future, if the app has strict validation, the address will be marked as illegal
- good compatibility
history mode
- The address is clean and beautiful
- Compatibility is slightly worse than hash mode
- When the application is deployed online, it needs the support of back-end personnel to solve the problem of refreshing the page server 404
(for example, http://localhost:8080/home/message, originally http://localhost:8080, when you click to go to the message page, the path It has changed, the path is still http://localhost:8080/home/message when refreshing, and /home/message will also be sent to the server, but people only know http://localhost:8080, hash will not be like this , http://localhost:8080/#/home/message, because nothing after # will be sent to the server)
source
Vue-router routing ultra-detailed tutorial
vue-router detailed explanation
article you take a quick understanding of Vue-Router routing