Vue routing basics

What is the

Routing: Routing is a mapping relationship.

Routing in Vue: mapping between paths and components;

why

Route functions: Switch service scenarios

Advantages:

  • Do not refresh the whole page, better user experience
  • Data transfer is easy and development efficiency is high

Disadvantages:

  • High development costs (need to learn expertise)
  • The first load will be a little slower. Is not conducive to seo

Single page application

Concept: All business is written on one page, with only one HTML

Benefits: High development efficiency, good user experience;

How to switch scenarios: Rely on route switching display

Vue-router is used basically

Concept: Vue-router is essentially a third-party package

Benefits:

  • It is deeply integrated with vue.js
  • Definable – visual chart (mapping rules)
  • modular
  • Provides two built-in global components
  • Declarative navigation automatically activates links to CSS classes

Steps:

  1. Download vuE-Router module to current project

yarn add vue-router 

  1. Introduce the VueRouter function in main.js

 import VueRouter from 'vue-router' 

  1. Add to vue.use () – Register global RouterLink and RouterView components

/ In vUE, any plug-in that uses VUE needs to be called vue.use ().

Vue.use(VueRouter)

  1. Create an array of routing rules – paths and component names
 1 const routes = [
 2   {
 3     path: "/find",
 4     component: Find
 5   },
 6   {
 7     path: "/my",
 8     component: My
 9   },
10   {
11     path: "/part",
12     component: Part
13   }
14 ]
Copy the code
  1. Generate routing objects with rules

const router = new VueRouter({  routes  }) 

  1. Inject the routing object into the new Vue instance

 1 new Vue({ router }) 

  1. Switch between different routing pages using router-view as the mount point

<router-view></router-view>  

Note: Everything is subject to the HASH value on the URL

Component classification

Page component: With routing, switch pages

Reuse components: page components that repeatedly render tags with the same structure

Declarative navigation

The base application

process

  1. Vue-router provides a global component, router-link
  2. Router-link essentially ends up rendering as a link to property is equivalent to providing href property (to doesn’t need #)
  3. Router-link provides declarative navigation highlighting (with class names)
  4. Set your own style
1 <template> 2 <div> 3 <div class="footer_wrap"> 4 <! -- a tag form --> 5 <! - < a href = "# / find" > find music < / a > 6 < a href = "# / my" > my music < / a > 7 < a href = "# / part" > friends < / a > -- > 8 and 9 < the router - the link To ="/find"> Find music </router-link> 10 <router-link to="/my"> My music </router-link> 11 <router-link to="/part"> Friend </router-link> 12  </div> 13 <div class="top"> 14 <router-view></router-view> 15 </div> 16 </div> 17 </template> 18 19 <script> 20 export default {}; 23 </script> 22 23 <style scoped> 24 /* Self-defined highlighting */ 25. footer_wrap. Router link-active {26 color: white; 27 background: black; 28 } 29 </style>Copy the code

Conclusion:

Router-link and to are used to switch routes. The a tag can be replaced by the global component router-link

Jump the participation

The syntax of the to attribute on router-link is as follows

  • /path ? Parameter name = Value
  • /path/ value – The route object needs to be configured with path: /path/ Parameter name

The corresponding page component receives the value passed:

  • $route. The query. The parameter name
  • $route. Params. Parameter name

In the column

components/Part.vue

1 < template > 2 < div > < p > 3 star watchers < / p > < p > 4 found wonderful < / p > < p > 5 looking for partners < / p > < p > 6 to join our < / p > < p > 7 names: {{ $route.query.name }} -- {{ $route.params.username }}</p> 8 </div> 9 </template>Copy the code

Route definition

1 {2 path: "/part", 3 Component: part 4}, 5 {6 path: "/part/ :username", // Path: "/part/ :username",Copy the code

Navigate the jump and pass the value to the myGoods.vue component

<router-link to="/part **? </router-link>

< the router - link to = "/ part/little wisdom * * * *" > friends - small blue < / router - the link >

Conclusion:

? Key =value $route.query.key;

/ in the route rule /path/:key, use $route.params.key

Redirection and pattern

redirect

  • The default hash value of the opening URL is/path
  • Redirect means to redirect the Settings to the default page.
1 const routes = [2 {3} path: "/", // Default hash path, must be /, cannot be followed by any other path "/find" // redirect to /find 5 // path after # in browser URL changed to /find- rematch array rule 6} 7]Copy the code

Summary: After a forcible redirection, the array matches the rule again

404 pages

Unable to find the page, default to a 404 page, used to remind the customer

Syntax: At the end of the route, path matches *(any path) – if it does not match the last one, the corresponding component page is displayed

In the column

Create the NotFound page

1 <template> 2 <img src=".. /assets/404.png" alt=""> 3 </template> 4 5 <script> 6 export default { 7 8 } 9 </script> 10 11 <style scoped> 12 img{ 13  width: 100%; 14 } 15 </style>Copy the code

In main.js – modify the route configuration

1 import NotFound from '@/views/NotFound' 2 3 const routes = [4 //... "*", 8 component: NotFound 9 } 10 ]Copy the code

Summary: If the route does not match any rules, give a bottom of the 404 page

Mode setting

Change the mode of routing in the address bar (with # in the path)

Hash route For example, http://localhost:8080/#/home—-> The hash path contains #

History routing for example: http://localhost:8080/home (after online need server-side support, or find the folder) — — — — — – > the history with no # in the path

router/index.js

Const router = new VueRouter({2 routes, 3 mode: "history" // hash 4})Copy the code

To use (JS code to jump) programmatically.

Based on using

Grammar:

 1 this.$router.push({

2 path: “route path “, // both go to router/index.js definition

3 name: “route name” 4})

Main.js – In the route array, name the route

 1 {
 2     path: "/find",
 3    name: "Find",  4     component: Find
 5 },
 6 {
 7     path: "/my",
 8     name: "My",  9     component: My
10 },
11 {
12     path: "/part",
13     name: "Part", 14     component: Part
15 },
Copy the code

App.vue – Switch to SPAN with JS programmatic navigation jump

1 <template> 2 <div> 3 <div class="footer_wrap"> 4 <span @click="btn('/find', 'Find') "> Find music < / span > 5 < span @ click =" BTN ('/my ', 'my') "> my music < / span > < span @ 6 click =" BTN ('/part, 'Part')"> friend </span> 7 </div> 8 <div class="top"> 9 <router-view></router-view> 10 </div> 11 </div> 12 </template> 13 14 $router. Push ({path: "router "}) 18 // this.$router. Push ({name:" router "}) "Route name "}) 19 // note: 20 // The hash value of the url is still changed to the hash value of the path 21 // scenario: 22 // convenient to change: Name Route name (not visible on the page) 23 // Path can be seen in the HASH value of the URL (try to comply with intra-group specifications) 24 export default {25 methods: This.$route. push({29 // path: targetPath, 30 name: targetName 31 }) 32 } 33 } 34 }; 35 </script>Copy the code

Jump the participation

The syntax query/params is optional

1 this.$router.push({2 path: "routing path" 3 name: "routing name ", 4 query: {5" parameter name ": value 6} 7 params: {8 "parameter name ": value 6} Value 9} 10}) 11 12 // The corresponding route receives $route.params. Parameter Name Value 13 // The corresponding route receives $route.query. Parameter Name ValueCopy the code

== Extra caution: Using path automatically ignores params==

App.vue

1 <template> 2 <div> 3 <div class="footer_wrap"> 4 <span @click="btn('/find', <span > 5 <span @click=" BTN ('/my', <span @click="oneBtn"> </span> 7 <span @click="twoBtn"> </span> 8 </div> 9 <div Class ="top"> 10 <router-view></router > 11 </div> 12 </div> 13 </template> 14 15 <script> 16 $route.params => $route.params Parameter name 19 // Method 2:20 // query => $route.query. Parameter name 21 // Major: Path will automatically ignore params 22 // Recommended: name+query 23 // Note: If the "hash value and? The parameter "hash "and the "hash" that you want to jump to? 24 export default {25 methods: {26 BTN (targetPath, targetName){27 // Mode 1: $router. Push ({29 // path: targetPath, 30 name: targetName 31 }) 32 }, 33 oneBtn(){ 34 this.$router.push({ 35 name: 'Part', 36 params: { 37 username: $router. Push ({43 name: 'Part', 44 query: {45 name: 'Part', 44 twoBtn(){42 this.$router. 46} 47}) 48} 49} 50}; 51 </script>Copy the code

Nested routing

The existing level-1 route is nested with the level-2 route

  1. Create all the components you need

    SRC /views/ find.vue — Find the music page

    SRC /views/ my.vue — My music page

    SRC/views/Second/how. Vue — — found that music page/Recommend the page

    SRC/views/Second/Ranking. Vue — — found that music page/list page

    SRC/views/Second/SongList. Vue — — found page music/song list page

  2. Main.js – Continue to configure level 2 routing

    Level 1 route path is defined from /

    For level-2 routes, the path name is directly written without the start of /

    Nested routines write routing information objects in the children array of the parent route

  3. Description:

    App. Vue’s router-View is responsible for discovering music and switching between my music page

    The router-view of find.vue is responsible for finding three pages under music, toggle

** find. vue configures secondary navigation **

1 <template> 2 <div> 3 <! - recommended < / p > < p > 4 list < / p > < p > 5 single < / p > < p > song - > 6 < div class = "nav_main" > 7 < the router - link to = "/ find/how" > recommended < / router - the link > 8 <router-link to="/find/ranking"> </router-link> 9 <router-link to="/find/ songList "> </router-link> 10 </div> 11 12 <div style="1px solid red;" > 13 <router-view></router-view> 14 </div> 15 </div> 16 </template> 17 18 <script> 19 export default {}; 20 </script> 21 22 <style scoped> 23 .nav_main { 24 background-color: red; 25 color: white; 26 padding: 10px 0; 27 } 28 .nav_main a { 29 text-align: center; 30 text-decoration: none; 31 color: white; 32 font-size: 12px; 33 margin: 7px 17px 0; 34 padding: 0px 15px 2px 15px; 35 height: 20px; 36 display: inline-block; 37 line-height: 20px; 38 border-radius: 20px; 39 } 40 .nav_main a:hover { 41 background-color: brown; 42 } 43 .nav_main .router-link-active{ 44 background-color: brown; 45 } 46 </style>Copy the code

Configuring routing rules – Displaying Secondary routes

3 {4 path: "/find", 5 name: "find", 6 Component: find, 7 children: [8 {9 path: "recommend", 10 component: Recommend 11 }, 12 { 13 path: "ranking", 14 component: Ranking 15 }, 16 { 17 path: "Songlist ", 18 Component: SongList 19} 20] 21} 22Copy the code

App.vue, the outer router-view is responsible for discovering music and switching between my music page

The router-view inside find. vue is responsible for switching components corresponding to subtabs under the music discovery

Conclusion: Nesting method, find which page to write router-view and corresponding rule to write children

The name of the class distinction

Router-link-exact -active Specifies the hash value of the URL, which is identical to the href value

Router-link-active Hash value in the URL, including the href value of the path

Global front guard

Before redirecting a route, run the front-guard function to check whether the route can be redirected normally

For example, before jumping to the route, the user can go to < my Music > page only if he/she logs in. If he/she does not log in, the popup window prompts him/her to return to the page of music discovery

Grammar:

Router.beforeeach ((to, from, next)=>{// Route jump "before" first perform here, decide whether jump})

mian.js

BeforeEach ((to, from, next)=>{// Route jump "before" do this first, decide whether to jump}) 4 // Parameter 1: Route to jump to (route object information) Target 5 // Parameter 2: Route from where to jump to (route object information) source 6 // Parameter 3: The function body -next () gives way to a normal jump switch, next(false) stays in place, next(" force change to another routing path ") 7 // Note: If next is not called, the page stays in place 8 9 // Example: /my 10 const isLogin = true; // Login status (not logged in) 11 router. BeforeEach ((to, from, Next) => {12 if (to.path === "/my" &&islogin === false) {13 alert(" Please log in ") 14 next(false) // Prevent route redirection 15} else {16 Next () // release 17} 18})Copy the code