Vue-Router
- Know the routing
- 1. What is routing
- 2. Back-end routing phase
- 3. Front-end routing phase
- Front-end routing rules
- 1. The URL hash
- 2.HTML5 history mode
- Vue basis – the Router
- 1. Know the vue – the router
- 2. Install and use the VuE-Router
- 3. Detailed routing components
- Route configuration Additional information
- 1. Default path of the route
- 2. History mode of the path
- 3. Add attributes of router-link and configuration routes
- 4. Programmatic navigation
- 5. Dynamic route matching
- The route was loaded lazily. Procedure
- 1. Recognize lazy route loading
- 2. Use lazy route loading
- Nested routing
- 1. Understand the embedded routine
- 2. The embedded routine is realized by
- 3. The default path of the set route
- Query gets parameters
- 1. Query retrieval
- 2. Parameter passing mode
- 3. The difference between router and route
- Navigation Guard ⚔
- 1. Get to know the navigation guard
- 2. Navigation guard use
- 3. Global rear hook
- 4. Route exclusive hook functions
- 5. Component hook functions
- Keep alive – components
- 1. Page caching
- 2. Keep alive – components
1. Know the route
1. What is routing (understanding)
- Routing explain
- Routing, “routing,” is the activity of transmitting information from a source address to a destination address over an interconnected network
- In routing, there is a very important concept called routing table
- The routing table is essentially a mapping table that determines where packets are headed
- The router
- Routers provide two mechanisms: routing and forwarding.
- Routing determines the path a packet takes from its source to its destination
- The transfer of data from the input to the appropriate output
- Routers provide two mechanisms: routing and forwarding.
Routing is to display different content or pages based on different UR addresses;
Routing is a general and abstract concept. The essence of routing is correspondence
2. Back-end routing phase
- In the early days of web development, the entire HTML page was rendered by the server
- The server will directly render the corresponding HTML page and respond to the client to show
- The back-end routing
- When the browser switches to a different URL in the address bar, it sends a request to the background server each time, and the server responds to the request
- In the background splicing HTML file to the front end display, return different pages
- That means the browser will refresh the page, or if the Internet is slow, the screen will be white and there will be new content. Another great problem with back-end routing is that the front and back ends are not separated
- Disadvantages of back-end routing
- The modules of the whole page are written and maintained by the back-end personnel, which is not easy to maintain
- Often the HTML code gets mixed up with the corresponding back-end logic code and is a terrible thing to write and maintain
3. Front-end routing phase
- Front and rear end separation stage:
- With the advent of Ajax, you have a development pattern that separates the front and back ends
- The back end only provides the API to return the data, and the front end retrives the data through Ajax and renders the data to the page through JS
- The biggest advantage of this is that the front and back end responsibilities are clear, the back end is focused on data, and the front end is focused on interaction and visualization
- And mobile (ISO/Android) after the emergence of the back-end does not need to do any processing, still use the previous set of API
- What is a SPA
- SPA is short for Single Page Web Application, translated as single Page Web Application
- Simply put, SPA is a Web project with only one HTML page. Once the page is loaded, SPA will not reload or jump to the page because of the user’s operation
- Instead, it uses JS to dynamically transform HTML content to simulate jumping between multiple views
- Single Page Rich Application (SPA)
- In fact, the most important feature of SPA is to add a layer of front-end routing on the basis of the separation of the front and back ends
- That is, the front end to maintain a set of rules
- What is the core of front-end routing?
- Change the URL, but the page does not refresh as a whole
Ii. Front-end routing rules
1. The URL hash
- The hash of the URL is the anchor point (#), which essentially changes the href property of window.location
- We can just assign
location.hash
Change href, but the page does not refresh
2.HTML5 history mode
- The History interface is a new addition to HTML5 and has five modes to change the URL without refreshing the page
history.pushState()
- Similar: in and out of the stack, first in and then out
history.replaceState()
- Replace URL without rollback
history.back()
- Go back to the last URL
history.forward()
- Advance the last URL
history.go(Number)
Number
: To advance or fall back to the specified URL
Vue-router Basic
1. Know the vue – the router
- Vue-router is the official vue.js routing plug-in. It is deeply inherited from vue.js and is used to build single-page applications (official document).
- Vue-router is based on routes and components
- Routes are used to set access paths and map them to components
- In a single page application of vue-Router, a change in the page path is a switch between components
2. Install and use the VuE-Router
-
Step 1: NPM installation
npm install vue-router --save
-
Step 2: Use it in the module project (since it is a plug-in, install the routing function through vue.use ())
-
(1) Import routing objects and call vue.use (VueRouter) to install routing functions
-
② Create a route instance and send the route mapping configuration
-
③ In the main entry file, import the created route instance and mount the route instance in the Vue instance
-
1. Configure vue-Router (figure)
-
-
Step 3: Use vue-router
-
Creating a Routing Component
-
Configuring route Mappings (Relationship between components and path mappings)
-
and
-
2. Use vue-router (figure)
-
3. Detailed routing components
-
: This tag is a built-in global component that is rendered as an
tag
to="path"
: This property is rendered ashref
attributeto="path"
The value of the: property is rendered with a # starting valuehash
addresspath
: Indicates the path configured in the route
-
: This tag dynamically renders the corresponding components based on the current path
-
During route switchover, the components mounted by
are switched, and other contents remain unchanged
Iv. Route configuration Other supplements
1. Default path of the route
Scene: Enter the homepage of the website and want
to render the contents of the homepage
- Add default path redirection to routing rules
const routes = [
{
// Configure the default path
path: '/'.
// Redirect to the /home path
redirect: '/home'
}
]
Copy the code
2. History mode of the path
Scenario: The page displays the URL, not the hash value #/home, but the normal URL: /home
- in
VueRouter
The instanceoption
Set in themode
forhistory
Model can be
// Create the VueRouter object
const router = new VueRouter({
routes,// Routing rules
mode: 'history'// The pattern of the URL display
})
Copy the code
3. Add attributes of router-link and configuration routes
<route-link>
Other propertiestag=""
: TAB can be specified<router-link>
What elements does the component render intoreplace
: There is no history record rollback, advance has no effectactive-class=""
: when<router-link>
When the corresponding path is successfully matched, one is automatically added to the current elementrouter-link-active
theclass
To set upactive-class
You can change the default name
<! -- tag: specifies what element the <router-link> component is rendered into -->
<!-- replace: 没有history记录,前后键没有用 -->
<! -- active-class: modified to match the default class name -->
<router-link to="/home" tag="button" replace active-class="active">Home page</router-link>
<router-link to="/about" tag="button" replace active-class="active">On the page</router-link>
Copy the code
- Configure route attributes:
linkActiveClass
- Function: when
<router-link>
If the corresponding path is successfully matched, the default class name is set
- Function: when
const router = new VueRouter({
routes,// Route mapping rules
mode: 'history'./ / mode
linkActiveClass: 'active'// Set the default match to add the ground class
})
Copy the code
4. Programmatic navigation
- Scenario: Not in use
<router-link>
Global component to jump to the URLthis.$router.push('path')
: to realize the redirect URL, there is a rollback history recordthis.$router.replace('path')
: to implement the redirect URL, without rolling back the history record
methods: {
home() {
// Do not use
global component to jump URL, how to implement
// this.$router. Push ('/home') // There is a rollback record
this.$router.replace('/home') // There is no rollback record
},
about() {
// this.$router.push('/about')
this.$router.replace('/about')
}
}
Copy the code
5. Dynamic route matching
-
In some cases, we need to set the path dynamically. For example, when we go to the user page, we want the following path to be displayed
- / user/aaa or/user/BBB
- In addition to the preceding /user, it is followed by the user ID
- This matching relationship between path and Component is called dynamic routing (also a way of routing data).
-
Procedure for dynamic route matching
-
1. Set dynamic route parameters
const routes = [{
path: '/user/:userId'.
component: User
}]
Copy the code -
2. Pass parameters in app. vue
-
3. The route component uses $route.params to obtain route parameters
-
-
graphic
5. Lazy route loading
1. Recognize lazy route loading
- The official explanation
- When you package to build an application, the JavaScript package can become very large and affect page loading
- It would be more efficient if we could split the components of each route into separate code blocks and then load the components when the route is accessed
- Why use lazy route loading?
- Our packaged files are usually placed in a JS file, which is bound to be very large
- If we request the file from the network at once, it may take a long time, or even a brief white-screen situation in the browser
- How to avoid this: Just use lazy route loading
- What does the route lazy load do?
- The main function of lazy route loading is to package the components corresponding to routes into js code blocks
- The component is loaded only when the route is accessed
2. Use lazy route loading
-
Method 1: Combine Vue’s asynchronous components with Webpack’s code analysis
- const Home = resolve => { require.ensure([‘../components/Home.vue’], () => { resolve(require(‘.. /components/Home.vue’)) })};
-
Method two: AMD writing method
- const About = resolve => require([‘../components/About.vue’], resolve);
-
Method 3: In ES6, we have a much simpler way of separating Vue asynchronous components from Webpack code
const Home = () => import('.. /components/Home.vue')
-
After packing effect
Routing nesting
1. Understand the embedded routine
- In the home page, we access some content through /home/news and /home/message
- One path maps another component, and accessing both paths also renders the two components separately
- The relationship between paths and components is as follows:
2. The embedded routine is realized by
- 1. Create a component
- 2. In the route mapping rule, configure the following nested rules:
children: [{},{}]
- 3. On the page where the component is to be nested, run router-link and router-view
3. The default path of the set route
- Nested routes can also have default paths
const routes = [
{
path: '/home'.
component: Home,
// Configure the set path
children: [
{
// Insert the default path of the path
path: ' '.
redirect: 'news'
},
{
path: 'news'.
component: News
},
{
path: 'message'.
component: Message
}]
}]
Copy the code
7. Query gets parameters
1. Query retrieval
- 1. Create a new component profile.vue
- 2. Configure route mappings
- 3. Add
to app. vue
<! -- 1. app. vue parameter passing -->
<router-link :to="{path: '/profile',query: {
name: 'wuyifan',
age: 18,
Height: 1.88
}}">archives</router-link>
<! -- 2.profile. vue -->
<h3>{{$route.query}}</h3>
Copy the code
graphic
2. Parameter passing mode
- There are two main types of passing parameters: params and Query
- params
- Configure the routing
path
:/user/:userId
- How to pass: The value to pass on the concatenation after path
- Gets the parameter passed:
$route.params.userId
- Configure the routing
- query
- Configure the routing
path
:/profile
(Common Configuration) - Method of delivery:
{path: '/profile', query: {name: 'yifan'} }
- Gets the parameter passed:
$route.query.name
- Configure the routing
- When you’re not using
<router-link>
To make the jump
this.$router.push({
path: '/profile'.
query: {
name: 'yifan'.
age: 18.
height: 1.88
}
})
Copy the code
3. The difference between router and route
$router
and$route
The difference between$router
Is the VueRouter instance for navigation operations related to the pathroute
Is the component object (currently active route object) of the current path mapping and can be obtainedpath, query
Parameters, etc.
8. Navigation Guard ⚔
1. Get to know the navigation guard
The vue-Router provides navigation guards that can be navigated by jumping or canceling
- Navigation guard
- Navigational guards are just some hook functions in a route jump, a route jump is a big process, a big process, a big process, a small process, and in each of those processes there’s a function that allows you to do something else, and that’s a navigational guard
vue-router
providesbeforeEach
andafterEach
These are fired before and after the route is about to change
Global hook function
- You can write the code logic directly in the routing configuration file router.js to do some global route interception
// Global front guard
router.beforeEach((to, from, next) = > {
// to: Route: indicates the destination Route object to be entered
// from: Route: the Route that the current navigation is leaving
// Proceed to the next hook in the pipeline. If all hooks are executed, then the state of the navigation is confirmed.
next();
});
// Global rear guard
router.afterEach((to, from) = > {
console.log(to.path);
});
Copy the code
2. Navigation guard use
- Consider one requirement: In a SPA application, how do you modify the title of a web page
- The first thing to think about is that each route corresponds to a component in the.vue file that passes
mounted
Life cycle function to modify the title - However, when there are many pages, this approach is not easy to maintain (because you need to execute similar code across multiple pages).
- Is there a better way? Use the navigation guard
- The first thing to think about is that each route corresponds to a component in the.vue file that passes
- Use the navigation guard in the route configuration file to modify the page title
// Define some titles in the hook, which can be defined using meta
const routes = [
{
path: '/user/:userId'.
component: User,
meta: {
title: 'users'
}
},
{
path: '/profile'.
component: Profile,
meta: {
title: 'archives'
}
}
]
// ------ Navigation guard -----------
router.beforeEach((to, from, next) = > {
// Jump from to to
// from: current $route object to jump to
// to: $route object after jump (some operations after jump)
// next(): after this method is called, the next hook can be entered
document.title = to.matched[0].meta.title;
next()
})
Copy the code
3. Global rear hook
- You can also register global post-hooks, but unlike the guard, these hooks will not accept them
next
Functions do not change the navigation itself
router.afterEach((to, from) = > {
// ...
})
Copy the code
4. Route exclusive hook functions
- Can do some individual route jump interception. Write code in the allocation file
const router = new VueRouter({
routes: [
{
path: '/foo'.
component: Foo,
beforeEnter: (to, from, next) = > {
// ...
}
}
]
})
Copy the code
5. Component hook functions
- More fine-grained route interception only intercepts one entry into a component
const Foo = {
template: `... `.
beforeRouteEnter (to, from, next) {
// Called before the rendering component's corresponding route is confirmed
/ / no! Can!!!! Get component instance 'this'
// Because the component instance was not created before the hook was executed
},
beforeRouteUpdate (to, from, next) {
// called when the current route has changed but the component is being reused
// For example, for a path with dynamic parameters /foo/:id, jump between /foo/1 and /foo/2,
// Since the same Foo component is rendered, component instances are reused. The hook will be called in that case.
// Can access component instance 'this'
},
beforeRouteLeave (to, from, next) {
// called when navigating away from the corresponding route of the component
// Can access component instance 'this'
}
}
Copy the code
Use scenarios for hook functions
In fact, the route hook function is not very much used in the project development, generally used for the login status check, no login jump to the login page; Verification of permissions and so on. Of course, as the project progresses, there will be more functionality and it might be better to do it with hooks, because we know that hooks are a good thing to do, and then the next time you have a problem, you can think, oh, this would be great to do it with hooks. We have achieved our goal.
Ix. Keep-alive component
1. Page caching
- In the single page application (SPA) built by Vue, the routing module is commonly used
vue-router
vue-router
Instead of saving the state of the component being switched, when it pushes or replcae, the old component is destroyed, the new component is created, and the entire lifecycle goes through again- However, sometimes we have some requirements, such as returning to the list page that the user clicked before the jump, but when we return there is no previous record, for this page caching requirement, we can use
keep-alive
Component to solve
2. Keep alive – components
keep-alive
Vue is a built-in component that enablesIncluded components retain stateOr,Avoid re-rendering- Two very important attributes:
inclue
: Values are strings or regular expressions, and only matching components are cachedexclue
: Values are strings or regular expressions, and any matching components are not cached- Note: The string matches the name attribute of the Vue component, if not configured
name
The keep-alive attribute will not take effect
- use
keep-alive
In:keep-alive
The view components in the package are cached
<! -- Profile,User is the name attribute in the Vue component (note that this does not work if it is not configured) -->
<keep-alive exclude="Profile,User">
<router-view></router-view>
</keep-alive>
Copy the code
- In addition, the activated and deactivated life cycle functions must be available only when the keep-alive component is used, otherwise they do not exist