1. Basic concepts and principles of routing
1.1. The routing
Routing is a relatively generalized and abstract concept, and the essence of routing is correspondence.
In development, routing is divided into:
- The back-end routing
- The front-end routing
1.1.1. Back-end routing
Concept: Return different content according to different user URL requests
Essence: The mapping between the URL request address and the server resource
1.1.1.1. SPA (Single Page Application)
- Back-end rendering (with performance issues)
- Ajax front-end rendering (front-end rendering improves performance, but does not support browser forward and backward operations)
- SPA (Single Page Application) : The entire website has only one Page. Content changes are implemented through Ajax partial updates, and the browser address bar can be moved forward and backward
- One of the principles of SPA implementation: URL-address-based hash (changes in hash will cause the browser to record changes in access history, but changes in hash will not trigger new URL requests)
- In the process of implementing SPA, the core technology is front-end routing
1.1.2. Front-end routing
Concept: Display different page content according to different user events
Essence: Correspondence between user events and event handlers
1.1.2.1. Simple front-end routing
- Implementation based on the HASH in the URL (change the HASH of the URL when clicking on the menu, control component switching based on the hash change)
// Listen for the window's onHashchange event and switch the name of the component to display based on the latest hash value
window.onhashchange = function() {
// Use location.hash to get the latest hash value
}
Copy the code
1.2. The Vue Router
Vue Router (router.vuejs.org/zh/) is the official route manager of Vue. It is deeply integrated with vue.js core, which can be very convenient for SPA application development. Vue Router provides the following functions:
- Support HTML5 historical mode or hash mode
- Support nested routines by
- Supported Routing parameters
- Support for programmatic routing
- Support named Routing
- Support for routing navigation guard
- Supports animation effects for route transitions
- Lazy route loading is supported
- Supports route rolling behavior
2. Basic use of vue-Router
2.1. Basic steps
- Import related library files
- Adding a Routing Link
- Add the route filling bit
- Defining routing Components
- Configure routing rules and create routing instances
- Mount the route to the Vue root instance
2.1.1. Introduce related library files
<! -- Import vue file, globalwindowObject mount Vue constructor --><script src=". / lib/vue_2. 5.22. Js. ""></script><! -- Import the vue-router file globallywindowObject mount VueRouter constructor --><script src=". / lib/vue - router_3. 0.2 js. ""></script>
Copy the code
2.1.2. Adding a routing link
<! -- Router-link is a tag provided in vue and will be rendered as a tag by default --> <! The to attribute is rendered as the href attribute by default --> <! -- The value of the to attribute is rendered as a hash address starting with # --><router-link to="/user">User</router-link>
<router-link to="/register">Register</router-link>
Copy the code
2.1.3. Adding the route filling bit
<! -- Route padding bit (also called route placeholder) --> <! -- Future components matched by routing rules will be rendered to the router-view location --><router-view></router-view>
Copy the code
2.1.4. Define routing components
var User = {
template: '<div>User</div>'
}
var Register = {
template: '<div>Register</div>'
}
Copy the code
2.1.5. Configure routing rules and create routing instances
// Create a route instance object
var router = new VueRouter({
// routes is an array of routing rules
routes: [
// Each routing rule is a configuration object that contains at least two attributes, path and Component: // Path represents the hash address matched by the current routing rule
// component Indicates the component that the current routing rule corresponds to
{path:'/user'.component: User},
{path:'/register'.component: Register}
]
})
Copy the code
2.1.6. Mount the route to the Vue root instance
new Vue({
el: '#app'.// In order for the rule to take effect, the routing object must be mounted to the VUE instance object
router
});
Copy the code
2.2. Route redirection
Route redirection means that when A user accesses address A, the user is forced to go to address C to display A specific component page. Using the redirect attribute of the routing rule, you can specify a new route address to conveniently set the route redirection:
var router = new VueRouter({
routes: [
// Path indicates the original address to be redirected, and redirect indicates the new address to be redirected
{path:'/'.redirect: '/user'},
{path:'/user'.component: User},
{path:'/register'.component: Register}
]
})
Copy the code
3. Vue-router nested routine
3.1. Nested routines depend on usage
3.1.1. Nested routines are analyzed by functions
- Click the parent route link to display the template content
- There are sub-routing links in the template content
- Click the sub-level route link to display the sub-level template content
3.1.2. Parent Routing component template
- Parent routing link
- Parent component route padding bit
<p>
<router-link to="/user">User</router-link>
<router-link to="/register">Register</router-link>
</p>
<div>
<! -- Control component display position -->
<router-view></router-view>
</div>
Copy the code
3.1.3. Sub-routing template
- Sub-routing links
- Padding bit of sub-route
const Register = {
template: '<div> < H1 >Register component </h1> <hr/> <router-link to="/ Register /tab1"> tab1 </router-link> <router-link to="/register/tab2">Tab2</router-link> <! -- Child route fill position --> <router-view/> </div> '
Copy the code
3.1.4. Nested routines are configured
- Parent route The children attribute is used to configure the child route
const router = new VueRouter({
routes: [{path: '/user'.component: User },
{
path: '/register'.component: Register,
// Add child routing rules to /register with the children attribute
children: [{path: '/register/tab1'.component: Tab1 },
{ path: '/register/tab2'.component: Tab2 }
]
}
]
})
Copy the code
4. Vue-router Matches dynamic routes
Dynamic routing is a form of routing that can receive parameter data. Part of the routing address may change
4.1. Basic usage of dynamic Matching routes
Think about:
<! - has the following3Routing links --><router-link to="/user/1">User1</router-link>
<router-link to="/user/2">User2</router-link>
<router-link to="/user/3">User3</router-link>
Copy the code
Is it feasible to define the following three routing rules?
{ path: '/user/1'.component: User }
{ path: '/user/2'.component: User }
{ path: '/user/3'.component: User }
Copy the code
Application scenario: Routes are matched based on dynamic route parameters
var router = new VueRouter({
routes: [
// Dynamic path parameters start with a colon
{ path: '/user/:id'.component: User }
]
})
Copy the code
const User = {
$route.params = $route.params = $route.params
template: '<div>User {{ $route.params.id }}</div>'
}
Copy the code
4.2. Routing components pass parameters
$route is highly coupled to the route, so you can use props to decouple the component from the route
The value of 4.2.1. Props is a Boolean
const router = new VueRouter({
routes: [
// If props is set to true, route.params will be set to the component property
{ path: '/user/:id'.component: User, props: true}]})const User = {
props: ['id'].// Use props to receive routing parameters
template: 'user ID: {{ID}}' // Use route parameters
}
Copy the code
The value of 4.2.2. Props is the object type
const router = new VueRouter({
routes: [
// If props is an object, it is set as a component property as-is
{ path: '/user/:id'.component: User, props: { uname: 'lisi'.age: 12}}}])const User = {
props: ['uname'.'age'].template: '<div> User information: {{uname +The '-' + age}}</div>'}Copy the code
4.2.3. The value of props is of function type
const router = new VueRouter({
routes: [
// If props is a function, the function accepts the route object as its parameter
{ path: '/user/:id'.component: User,
props: route= > ({ uname: 'zs'.age: 20.id: route.params.id })}
]
})
const User = {
props: ['uname'.'age'.'id'].template: '<div> User information: {{uname +The '-' + age + The '-' + id}}</div>'}Copy the code
5. Vue-router Named the route
5.1. Configuration rules for named Routes
To better represent the route path, you can alias the routing rule named Route.
const router = new VueRouter({
routes: [{path: '/user/:id'.name: 'user'.component: User
}
]
})
<router-link :to="{ name: 'user', params: { id: 123 }}">User</router-link>
router.push({ name: 'user'.params: { id: 123 }})
Copy the code
Vue-router programmatic navigation
6.1. Two ways of page navigation
- Declarative navigation: The way to navigate by clicking on a link, called declarative navigation, such as a link in a regular web page or a VUE
- Programmatic navigation: Called programmatic navigation by calling aN API in the form of JavaScript, such as location.href in a regular web page
6.2. Basic usage of programmatic navigation
Common programmatic navigation apis are as follows:
- This $router. Push (‘ hash address)
- this.$router.go(n)
const User = {
template: '
< button@click ="goRegister">
.methods: {
goRegister: function(){
// Control route hops programmatically
this.$router.push('/register'); }}}Copy the code
Parameter rules for router.push() methods
// String (path name)
router.push('/home')
/ / object
router.push({ path: '/home' })
// Named route (pass parameters)
router.push({ name: '/user'.params: { userId: 123 }})
// With query parameters, change to /register? uname=lisi
router.push({ path: '/register'.query: { uname: 'lisi' }})
Copy the code