1. What is routing?
Routing is the mapping relationship between path and component
one point one Why use routing?
-->In one page, switch business scenarios
Single page application (SPA): all functions are implemented on one html page
Front end routing function: realize business scenario switching
1.2 Routing - component classification
There are two types of. vue files, one is page component and the other is reuse component
The. vue file is essentially indistinguishable, convenient for learning and understanding, and a summary of experience
Src / views (or pages) folder and src/components folder
-
Page component - Page presentation - used with routing
-
Reuse component - display data / commonly used for reuse
Summary: the page components under views cooperate with route switching. The components under views are generally introduced into vue under views to reuse display data
2. Use of Vue router
install
yarn add vue-router
Import route
import VueRouter from 'vue-router'
Using routing plug-ins
// In vue, Vue.use() needs to be called for plug-ins using vue Vue.use(VueRouter)
Create routing rule array
const routes = [ { path: "/my", component: Home }, { path: "/login", component: Login }, { path: "/reg", component: Register } ]
Create routing object - incoming rule
const router = new VueRouter({ routes })
Associate to vue instance
new Vue({ router })
Replace components with router view
<router-view></router-view>
Summary: download the routing module, write corresponding rules and inject them into the vue instance. Use the router view mount point to display the switched routes
3. vue Routing - declarative navigation
3.1 declarative navigation - basic use
-
Vue router provides a global component router link
-
Router link will eventually render as a link. The to attribute is equivalent to providing the href attribute (to does not need #)
-
Router link provides the function of declarative navigation and highlighting (with its own class name)
<template> <div> <div class="footer_wrap"> <router-link to="/find">Discover music</router-link> <router-link to="/my">My collection</router-link> <router-link to="/part">My attention</router-link> </div> <div class="top"> <router-view></router-view> </div> </div> </template> <script> export default {}; </script> <style scoped> /* Other styles are omitted */ .footer_wrap .router-link-active{ color: white; background: black; } </style>
three point two Declarative navigation - jump parameters
Pass the value of the to attribute on the router link. The syntax format is as follows
-
/path? Parameter name = value
-
/Path / value - the routing object needs to configure path in advance: "/ path / parameter name"
The corresponding page component receives the passed value
-
$route.query. Parameter name
-
$route.params. Parameter name
1. Create components/Part.vue - prepare to receive the parameters and values passed on the route
<template> <div> <p>Find wonderful</p> <p>Find partners</p> <p>Join us</p> <p>name: {{ $route.query.name }} -- {{ $route.params.username }}</p> </div> </template>
2. Route definition
{ path: "/part", component: Part }, { path: "/part/:username", // Yes: the path represents the specific value to be received component: Part },
3. Navigate to jump and pass the value to MyGoods.vue component
<router-link to="/part?name=Zhang San">follow-Zhang San</router-link> <router-link to="/part/Li Si">follow-Li Si</router-link>
Summary:
? key=value use $route.query.key to get the value
/The value is taken in advance in the routing rule / path/:key with $route.params.key
4 vue Routing - redirection and mode
four point one Routing redirection
After matching the path, forcibly switch to the target path
-
The default hash value of web page opening url is / path
-
Redirect is to set which routing path to redirect to
For example, the web page opens by default, matches the route "/", and forcibly switches to "/ my"
const routes = [ { path: "/", // Default hash value path redirect: "/my" // Redirect to / my // The path in # the browser url is changed to / my - rematch array rule } ]
Summary: if you force the reset backward, you will match the rules in the array again
four point two Routing - 404 page
If the routing hash value does not match the rules in the array, it is given to a 404 page by default
Syntax: at the end of the route, the path matches * (any path) – if the previous does not match, the last one will be hit, and the corresponding component page will be displayed
1. Create NotFound page
<template> <img src="../assets/404.png" alt=""> </template> <script> export default { } </script> <style scoped> img{ width: 100%; } </style>
2. In main.js - modify the routing configuration
import NotFound from '@/views/NotFound' const routes = [ // ... other configurations are omitted // 404 at the end (the rule is to compare paths one by one from front to back) { path: "*", component: NotFound } ]
Summary: if the route fails to hit any rules, a 404 page is given
four point three Routing - mode settings
hash routing, for example: http://localhost:8080/#/home
history routing, for example: http://localhost:8080/home (server side support is required to go online, otherwise the folder is found)
In router/index.js:
const router = new VueRouter({ routes, mode: "history" // Background support is required after packaging and going online. The mode is hash })
five vue Routing - programmed navigation
five point one Programming navigation - basic use
-->Jump with JS code
Syntax:
this.$router.push({ path: "Routing path", // Go to router/index.js definition name: "Route name" })
1.main.js - name the route in the route array
{ path: "/find", name: "Find", component: Find }, { path: "/my", name: "My", component: My }, { path: "/part", name: "Part", component: Part },
2.App.vue - change to span with js programmed navigation jump
<template> <div> <div class="footer_wrap"> <span @click="btn('/find', 'Find')">Discover music</span> <span @click="btn('/my', 'My')">My music</span> <span @click="btn('/part', 'Part')">friend</span> </div> <div class="top"> <router-view></router-view> </div> </div> </template> <script> // be careful: // Although the name is used to jump, the hash value of the url still switches the path value // Scenario: // Easy to modify: name route name (can't be seen on the page, just defined) // The path can be seen in the hash value of the url (try to conform to the specifications within the group) export default { methods: { btn(targetPath, targetName){ // Method 1: path jump this.$router.push({ // path: targetPath, name: targetName }) } } }; </script>
5.2 programmed navigation - jump transfer parameters
Syntax query / params optional
this.$router.push({ path: "Routing path" name: "Route name", query: { "Parameter name": value } params: { "Parameter name": value } }) // The corresponding route receives the value of $route.params. Parameter name // The corresponding route receives the value of $route.query. Parameter name
App.vue
<template> <div> <div class="footer_wrap"> <span @click="btn('/find', 'Find')">Discover music</span> <span @click="btn('/my', 'My')">My music</span> <span @click="oneBtn">follow-Jay Chou</span> <span @click="twoBtn">follow-Eason Chan</span> </div> <div class="top"> <router-view></router-view> </div> </div> </template> <script> // Mode 1: // Params = > $route.params. Parameter name // Mode 2: // Query = > $route.query. Parameter name // Important: path automatically ignores params // Recommendation: pass parameters in name+query mode // Note: if the "hash value and" parameter "on the current url are consistent with the" hash value and "parameter" you want to jump to, the problem of redundant navigation will arise and the route will not be jumped export default { methods: { btn(targetPath, targetName){ // Method 1: path jump this.$router.push({ // path: targetPath, name: targetName }) }, oneBtn(){ this.$router.push({ name: 'Part', params: { username: 'Small' } }) }, twoBtn(){ this.$router.push({ name: 'Part', query: { name: 'Xiao Zhi' } }) } } }; </script>
6. vue Routing - nesting and guarding
6.1 vue Routing - route nesting
-->Under the existing primary route, the secondary route is nested
Router view nested architecture diagram
-
Create all components needed
src/views/Find.vue -- discover music pages
src/views/My.vue -- my music page
src/views/Second/Recommend.vue -- discover music page / recommend page
src/views/Second/Ranking.vue -- discover music page / leaderboard page
src/views/Second/SongList.vue -- discover music page / song list page
-
main.js – continue configuring Level 2 routing
The first level routing path is defined from /
The second level route writes the name directly after the path, and does not need to start with /
Nested routing writes a routing information object in the children array of the parent route
-
explain:
The router view of App.vue is responsible for discovering music and my music page and switching
The router view of Find.vue is responsible for finding three pages under music and switching
1. Configure secondary navigation and style -- in Find.vue
<template> <div> <!-- <p>recommend</p> <p>Ranking List</p> <p>song sheet</p> --> <div class="nav_main"> <router-link to="/find/recommend">recommend</router-link> <router-link to="/find/ranking">Ranking List</router-link> <router-link to="/find/songlist">song sheet</router-link> </div> <div style="1px solid red;"> <router-view></router-view> </div> </div> </template> <script> export default {}; </script>
2. Configure routing rules - Secondary routing display
const routes = [ { path: "/find", name: "Find", component: Find, children: [ { path: "recommend", component: Recommend }, { path: "ranking", component: Ranking }, { path: "songlist", component: SongList } ] } ]
3. Description:
-
App.vue, the outer router view is responsible for finding music and switching my music pages
-
The router view in the inner layer of Find.vue is responsible for finding the component switching corresponding to the sub tab under music
4. Run - click navigation to observe where nested routes are displayed
Summary: nested routing, find out which page to write router view and children in the corresponding rules
5.2 declaration navigation - class name difference
-
The hash value path in the router link exact active (exact match) url is exactly the same as the href attribute value. Set this kind of name
-
The hash value in the router link active url contains the path of the href attribute value
five point three Global front guard
Before route jump, execute the pre guard function once to judge whether it can jump normally
1. Use the fixed method beforeEach on the routing object
// Syntax: router. Beforeeach ((to, from, next) = > {/ / execute "before" route jump. Here, decide whether to jump}) // Parameter 1: route (route object information) target to jump to // Parameter 2: where to jump route (route object information) source // Parameter 3: function body - next() will make the route jump and switch normally, next(false) will stay in place, and next ("forced modification to another route path") // Note: if next is not called, the page remains in place const isLogin = true; // Login status (not logged in) router.beforeEach((to, from, next) => { if (to.path === "/my" && isLogin === false) { alert("Please login") next(false) // Prevent route jump } else { next() // Normal release } })
Summary: next() is released, next(false) remains in place and does not jump the route, and next(path) is forcibly changed to the corresponding path to jump