Basic concepts and principles of routing
Routing is introduced
-
Routing is a generalized and abstract concept. The essence of routing is one-to-one correspondence
-
There are two kinds of routes in development
- The front-end routing
- The back-end routing
-
The essence of a route is a mapping relationship. For example, enter a URL address in the address bar to obtain the corresponding URL resource
-
Routes are classified into front-end routes and back-end routes
- Front-end routing is implemented by changing the hash value (the relationship between anchors and components), that is, the anchor join of the A tag
- The basic concept of front-end routing is to display different page contents according to different events, and the corresponding relationship between events and event handlers
- The main thing front-end routing does is listen for events and execute corresponding event handlers
- Back-end routing is implemented on the server side and distributes resources (urls to resource data)
- The performance of back-end routes is lower than that of front-end routes
The back-end routing
-
Back-end routes
-
conclusion
- The back-end rendering page, as long as a change in the page, the need to refresh the entire page, there are performance issues
- Ajax is a technique that partially updates a web page, but does not support moving forward or backward
The front-end routing
-
Front-end Routing
- Locally update the page content based on changes in the address bar (without sending Ajax requests)
- Switch front-end service scenarios
-
Front end – Implementation principles
-
The # in the address bar has two meanings
-
Anchor link: Jump to the current page
-
The hash value does not refresh the current page when it changes, but its change triggers the hashchange event,
The core implementation relies on Hashchang events, which listen for changes in hash values
window.onhashchange = function(){ //location.hash Retrieves the latest hash value location.hash } Copy the code
-
-
-
conclusion
- Routing: A one-to-one mapping between a URL address and a URL resource
- Back-end routing: One-to-one mapping between urls and service resources
- Front-end routing: The one-to-one mapping between user events and event handlers, such as clicking a button on a page to change the HASH value of the URL, and switching components based on the hash value change
SPA
-
The SPA is introduced
- Single page application, abbreviated as SPA (Single Page Application), all functions of a project are realized on one page (more on the mobile terminal, as long as the project is developed with Vue, most of it is SPA).
- One of the principles of SPA implementation: Based on the HASH value of the URL address (changes in the hash will cause the browser to record changes in the access history, but changes in the hash will not trigger new URL requests)
- SPA realizes service scenario switching through front-end routing.
- The SPA can be partially updated and also supports forward and backward updating
- Vue-router can be used to implement front-end routing services easily
-
The characteristics of
- Advantages: Better user experience without refreshing the page
- Disadvantages: the first load will be a bit slower, there will be a way to optimize
Vue-router basic use
-
introduce
- Vue. Js officially provides the route manager, is a powerful front-end router, recommended use
- Vue Router and Vue. Js are very compatible and can easily implement SPA(Single Page Web Application) application development
- The vue Router depends on vue.js and must be imported from vue.js before the Vue Router
- Vue Router official website router.vuejs.org/zh/
-
Vue Router features
- Supports H5 historical mode or hash mode
- Embedded routing
- Supported Routing parameters
- Support for programmatic routing
- Support named Routing
- Navigation guard
- Route lazy loading
- Transition dynamic effect
- .
Using the step
-
Import the Vue Router file (you must import the vue.js file before doing this)
-
Adding a Routing Link
-
Add a routing point character (the last component to be displayed will be displayed at the point character)
-
Defining routing Components
-
Configure routing rules and create routing instances
-
Mount the route to the Vue instance
-
The introduction of Vue router
<! Mount vue constructor for global Window object --> <script src=". / lib/vue_2. 5.22. Js. ""></script> <! Mount VueRouter constructor for global window object --> <script src=". / lib/vue - router_3. 0.2 js. ""></script> Copy the code
-
Adding a Routed Connection
<! -- Router-link is a tag provided by the route, which is rendered as a tag by default. <! -- The to attribute is rendered as href by default --> <! The value of the to attribute will be rendered as a hash address starting with # --> <router-link to="/user">User</router-link> Copy the code
-
Add route placeholders
<! -- Future components matched by routing rules will be rendered to the router-view location --> <router-view></router-view> Copy the code
- Router-view: indicates the router-view. Users click the route link to display the corresponding component
-
Defining routing Components
var User = { template:"<div>This is User</div>" } var Login = { template:"<div>This is Login</div>"}Copy the code
-
Create a routing instance and configure routing rules
// Create a route instance object var router = new VueRouter({ //routes is an array of routing rules routes: [// Each routing rule is an object containing at least two attributes, path and Component // Path indicates the hash address matched by the route. //component indicates the routing rule corresponding to the component object to be displayed {path:"/user".component:User}, {path:"/login".component:Login} ] }) Copy the code
-
Mount the route to the Vue instance
// Mount the route to the Vue instance new Vue({ el:"#app".// In order for the rule to take effect, the routing object must be mounted on the Vue instance router }) Copy the code
- The parameters EL, data, methods, and Router are fixed during Vue instantiation
Route redirection
-
Route redirection means that when A user accesses ADDRESS A, he or she is forced to redirect to address C to display A specific component page. You can easily configure route redirection by specifying A new route address using the redirect attribute of routing rules
var router = new VueRouter({ //routes is an array of routing rules routes: [ // Set path to/to indicate the initial page address /. Redirect indicates the new address to be redirected { path:"/".redirect:"/user"}, { path: "/user".component: User }, { path: "/login".component: Login } ] }) Copy the code
- Application: When I open the page, the default address is #/ root. I want to open the page and access: #/user, so I use the override direction
Route-404 page
-
When we visit a page that does not exist, give the user a prompt to visit a 404 page
-
If the other routing rules are not matched successfully, use * to ensure the bottom
-
Format: {path: ‘*’, Component: {template: ‘
The page you’re looking for is eaten by aliens ~~~‘}}
const router = new VueRouter({ // routes: Configures the routing rule routes: [ // * indicates all, implementing 404 pages // If none of the other rules match, go here { path: The '*'.component: { template: '
The page you are looking for has been eaten by aliens ~~~'}}}])Copy the code
Embedded routines by
-
Click the parent route link to display the template content. If there are child routes in the template content, click the child routes to display the corresponding content
-
For example, if we have a parent Login route, we can add child routes/Login/Account and/Login /phone
<head> <meta charset="UTF-8" /> <meta name="viewport" content="Width = device - width, initial - scale = 1.0" /> <meta http-equiv="X-UA-Compatible" content="ie=edge" /> <title>Document</title> <! -- Import vue file --> <script src=". / lib/vue_2. 5.22. Js. ""></script> <script src=". / lib/vue - router_3. 0.2 js. ""></script> </head> <body> <! -- Area controlled by vm instance --> <div id="app"> <router-link to="/user">User</router-link> <router-link to="/register">Register</router-link> <! -- Route placeholder --> <router-view></router-view> </div> <script></script> </body> Copy the code
-
Conclusion:
- Child routing rules are defined in the parent routing rules, and router-view and router-link are written in the parent routing template
Vue-router Matches dynamic routes
Dynamic Route Matching
-
Application scenario: Routes are matched based on dynamic route parameters
<body> <! -- Area controlled by vm instance --> <div id="app"> <router-link to="/user/1">User1</router-link> <router-link to="/user/2">User2</router-link> <router-link to="/user/3">User3</router-link> <router-link to="/register">Register</router-link> <! -- Route placeholder --> <router-view></router-view> </div> <script> / / component const User={ $route.params = $route.params = $route.params template:{{$route.params.id}} } var router = new VueRouter({ //routes is an array of routing rules routes: [ // Pass parameters as /: parameter names { path: "/user/:id".component: User }, ] }) // Create the VM instance object const vm = new Vue({ // Specify the area to control el: '#app'.data: {}, // Mount the route instance object // router: router router }) </script> </body> Copy the code
-
When a matching rule is defined, the syntax of dynamic routes is ** : Parameter name **, which starts with a colon, indicates dynamic matching
-
When the route component is defined, the route parameter is {{$route.params. Parameter name}}
-
{{$route.params.}} is fixed
-
Props transfer parameter
-
Introduces the props
- $route.params is highly coupled to the route, so you can decouple the component from the route using props
- There are three types of props: props is of the Boolean type, object type, and function type
-
The value of props is of a Boolean type
var User = { props: ["id"].// Use props to receive routing parameters template:User: {{id}} // Use route parameters } var myRouter = new VueRouter({ //routes is an array of routing rules routes: [ // Pass parameters as /: parameter names // If props is set to true, route.params will be set to the component property { path: "/user/:id".component: User,props:true},]Copy the code
- In the route definition rule, props:true indicates that props is enabled to transfer dynamic parameters
- In the routing component definition: receives parameters through props
-
The value of props is the object type
var User = { props: ["username"."pwd"].template:User: {{username}}-- {{PWD}} } var myRouter = new VueRouter({ //routes is an array of routing rules routes: [ // Pass parameters as /: parameter names // If props is set to object, then data from the object is passed to the component { path: "/user/:id".component: User, props: {username:"jack".pwd:123}}}])Copy the code
- The jacki of username is passed to the username of props in the User component, and the 123 of PWD is passed to the PWD of props in the User component
- The ID is not available, so the ID is lost in this way
- The: ID is passed to the User as an argument only if props is true
-
The value of props is of function type
var User = { props: ["username"."pwd"."id"].template:
User: {{id}} -> {{username}}-- {{PWD}}} var myRouter = new VueRouter({ //routes is an array of routing rules routes: [ // Pass parameters as /: parameter names // If props is set to function, the route object is obtained by the first argument of the function // The params property of the route object can be used to obtain the passed parameters { path: "/user/:id".component: User, props:route= >{ return {username:"jack".pwd:123.id:route.params.id} } } ] }) Copy the code
-id: route.params.id: route.params.id: route.params.id: route.params.id: route.params.id: route.params.id This.$router.query.id ' 'js // Parameter id=1&age=3 <router-link to="/user? Id =1&age=3">query </router-link> var User = {// $route.query '<div> {{$route.query.id}} - {{$route.query.age}}</div>'} var router = new VueRouter({//routes) [ { path: "/user", component: User } ] })Copy the code
Named routing and programmatic navigation
### Name the route
- To better represent the route path, you can alias the routing rule named Route.
// Routing links
<router-link :to="{ name:'user' , params: {id:123} }">User</router-link>
const router = new VueRouter({
//routes is an array of routing rules
routes: [
// Add an alias for the route via the name attribute
{
path: "/user/:id".component: User,
name:"user" // Name the route]})},Copy the code
- Sometimes the path is complex, and it is better to use a named route instead
- If there are parameters in path, the value of the parameter is determined by params in TO
Programmatic navigation
-
Two ways to navigate a page
-
Declarative navigation: Navigation by clicking on links is called declarative navigation
-
Programmatic navigation: The way to achieve navigation by calling APl in the form of javaScript is called programmatic navigation
For example, location.href in a regular web page
- Declarative navigation: HTML implementation navigation
- Programmatic navigation: js code for navigation (location.href is js code)
- Programmatic routing jump:
This $router. Push ("/register ")
-
-
Programming navigation
-
A common programmatic navigation API
this.$router.push (hash address)// Jump to the corresponding component based on the hash value this. $router. Go (n)N represents the value '-1' backward '1' forward Copy the code
cons User={ template:'
< button@click ="goRegister">Methods: {goRegister:function(a){ // Control route hops programmatically this. $router. Push ("/register"); }}}Copy the code- Push jump anchor point
- Go forward and backward, parameter N is a number, representing the forward and backward interfaces
- N indicates n interfaces
- -n: indicates that n interfaces are backward
-
Push parameters (understood)
-
introduce
-
Route-link provides the same function as route-link
-
So you can write path paths (routes) directly in push, or you can write named routes
-
Is equivalent to:
<! -- The first two correspond to this --> <router-link to="/home">User1</router-link> <! #push (name) #push (name) <! -- Named route (pass parameters) --> <router-link :to="{ name: 'user', params: {userId: 123} }">User123</router-link> <! Register? uname=lisi --> <router-link to="/register? uname=lisi">Register</router-link> Copy the code
Navigation guard
-
Add a layer of interception after the route jump and do our own thing
-
Actual application scenario: Login
- If you’re currently logged in, I’m going to tell you to jump to the list page L if you’re not logged in, I’m going to tell you to jump, and I’m not going to let you jump
router.beforeEach((to, from, next) = > { console.log('Current route jumped') next() }) // to: represents the detail route object // from: indicates the source object of route redirection // Next: Execution of the next function determines whether a jump can be made or not. // Simulate login verification const loginFlag = false router.beforeEach((to, from, next) = > { // Determine whether you are logged in loginFlag True Login false No login if(! loginFlag) {// Prompt login if not logged in alert('Please login first! ')}else { // Jump if logged in next() } }) Copy the code
“Likes, favorites and comments”
❤️ follow + like + favorites + comments + forward ❤️, encourage the author to create a better article, thank 🙏 everyone.