Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the routes configuration of Vue-Router

2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly explains "what is the routes configuration of Vue-Router". The content of the explanation is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "what is the routes configuration of Vue-Router".

Catalogue

Introduction

Object properties in routes

Path: string

Component: Component | () = > import (component)

Name: string

Redirect: string | Location | Function

Props: boolean | Object | Function

Alias: string | Array [string]

Children?: Array [RouteConfig]

BeforeEnter: (to: Route, from: Route, next: Function) = > void

The example method of Router

* VueRouter instance properties

VueRouter instance method

Router.push (string | location)

Router.replace (string | location)

Router.go (Int number)

Router.back ()

Router.forward ()

Routing lazy loading

Do not use lazy loading

Use lazy loading

History mode and hash mode

History mode

Hash mode

Routing guard

Global routing guard

Situation one

Case two

Situation three

Introduction

In projects that use vue-router, instantiating VueRouter is its configuration option routes, which specifies the relationship between routes to the components of the view or to other routes, of which Router configuration options are the most important.

Object properties in routes

Interface RouteConfig = {path: string, component?: Component, name?: string, / / named routing * components?: {[name: string]: Component}, / / named view component https://router.vuejs.org/zh/guide/essentials/named-views.html#%E5%B5%8C%E5%A5%97%E5%91%BD%E5%90%8D%E8%A7%86%E5%9B%BE redirect?: string | Location | Function Props?: boolean | Object | Function, alias?: string | Array, children?: Array, / / nested route beforeEnter?: (to: Route, from: Route, next: Function) = > void, * meta?: any, / / 2.6.0 + * caseSensitive?: boolean, / / is the matching rule case sensitive? (default: false) * pathToRegexpOptions?: Object / / compile regular option} path: string

Specify the path of the current route. When the browser url matches path, router-view will render the current route object and specify the view component component/components.

Const routes = [{path:'/', component: Home}, {path:'/user', component: User}] const router = new VueRouter ({routes})

Note that Vue's router supports dynamic paths in the form of "/: attribute name" as part of the current path string. This string route will be used as a dynamic route to match the response string information on the real url

Const routes = [{path:'/', component: Home}, {path:'/user/:id/:local', / / dynamic path: id: local component: User}] const router = new VueRouter ({routes }) / / Route Jump / / the following links will match / user/:id/:local user 007 user 111user 10086 user 241247 * when we jump to the above route, its corresponding route view component User can obtain dynamic path matching information through this.$route.params example: url / user/007/lk this . $route.params-> {id:'007' Local:'lk'} url / user/10086/yk this.$route.params-> {id:'10086',local:'yk'} * /

Note that this.$route is the information object routed by the current vue application.

/ / http://localhost:8080/#/user/10086/cc?wd=iPhone&aa=test{ name: undefined, / / current route name * fullPath: "/ user/10086/cc" / / current url full path * hash: "/ / current route hash * matched: [{… }] * meta: {} params: {id: "10086", local: "cc"} / / dynamic path matching to the key pair object * path: "/ user/10086/cc" / / the query string URL of the current url matching path query: {/ / url? The object parsed by the following parameters wd: "iPhone", aa: "test"}} component: Component | () = > import (component)

The routing component rendered when the current browser url matches the path of the route

Import Vue from 'vue'import HotMusicList from'.. / views/HotMusicList'const routes = [{path:'/ hot', component: HotMusicList}, {/ / dynamic path matching gets the lazy loading of different id path: / music/:id', / / routing for each song through: id. In the form of a function, you can specify which components in the project are not allowed to be loaded at the beginning. Load into the project / / the routing component will be loaded into the project only if the browser jumps to the current route / / the advantage of this is that it reduces unnecessary loading and reduces application loading speed and running bandwidth component: () = > import ('.. / views/MusicPlay')}]

Note that for routing components that do not need to be loaded at the beginning in project development, please use lazy loading

Name: string

Name the route to make it a named route. The navigation of the route can be redirected using name. (when routes use location navigation, only named routes can directly accept pramas parameters)

Const routes = [{path:'/ user', name: 'User', component: () = > import ('.. / views/User.vue')}] redirect: string | Location | Function

Redirect route to which the current application access navigates (in the form of replacement) automatically redirects to the new route specified by redirect

Const routes = [{path:'/ contact', component: ContactView}, {path:'/ user/:id', name: 'User', component: () = > import ('.. / views/User.vue')}, {path:'/ oldpath2', redirect:'/ contact'}, {path:'/ oldpath3', redirect: {name: 'User' Params: {name: 'Xiao Ming', age: 19}}, / * redirect supports the form of a function that takes an argument as a location object generated when accessing oldpath. The redirect function must return redirected path or location * / {path:'/ oldpath3', redirect: (oldpathLocation) = >'/ contact'} {path:'/ oldpath5'. Redirect: (oldpathLocation) = > {name: 'User', params: {name:' Xiaoming', age: 19}] props: boolean | Object | Function

Dynamic matching of routes in general, the dynamic matching value can only be obtained through this.$route.params. When the props property is set, the dynamically matched key-value pairs can be passed directly to the view component as a component props, which greatly reduces the coupling of the component.

Boolean value. If props is set to all key-value pairs of true,route.params, it will be set to the component props property.

Const routes = [{path:'/ hot', component: HotMusicList}, {/ / dynamic path matching gets different id path of each song through: id: / music/:id', / / routing lazy loading component: () = > import ('.. / views/MusicPlay') Props: true}] / / the this.$route.id song playback export default {props: ['id'], / / the key-value pair matched by the dynamic path is automatically passed to the same name props data () {return {musicUrl:''}} of the current component through the id of this.$route.id Created () {fetch (`/ song/url?id=$ {this.id}`) .then ((res) = > res.json ()) .then (({data}) = > {/ / in real development, it is necessary to determine whether the data request is successful console.log (data [0]) / / assign the data of the song to data this.musicUrl = data [0]? .url});},}

Object props object form, that is, the object key is used as the rendering component props attribute name, and value is the corresponding attribute value (this way of writing value does not change, so passing props is some static properties)

{path:'/ home/:id', name: 'Home', props: {a: 1, b: false}, component: Home}

The function writing of the function props takes the current routing information object as an argument, and the function returns an object. The key of the object is the props attribute name of the rendering component, and the value is the corresponding attribute value.

{path:'/ home/:id', name: 'Home', props: (route) = > ({a: route.query.wd, / / pass route query.wd to component Home a props b: route.params.id / / pass route params.id to component Home b props}), component: Home} alias: string | Array [string]

An alias for a route that allows you to set multiple paths to a route. When accessing these alias paths, they all access the same routing component

Const routes = [{path:'/ hot', component: HotMusicList, alias: ['/ list','/rank','recommend']}] children?: Array [RouteConfig]

Nested routes, you can set a secondary route for the current route

[{path:'/ home', component: Home, children: [{path:'/ home/follow', component: () = > import ('.. / views/home/Follow')}, {path: 'recommend' / / do not add / relative path before routing is equivalent to "/ home/recommed" component: () = > import ('.. / views/home/Recommend')}]}] beforeEnter: (to: Route, from: Route, next: Function) = > void

The exclusive guard of the route. When the application is about to navigate to the current route, you can use the guard to perform some logical operations to realize whether to block the navigation.

The example method of Router

When the concept configures the VueRouter instance object into Vue, the vue instance has a this.$router property, and this.$router is the instance object of the current VueRouter. He provides API for all programmatic navigation.

Note that router is the property method containing routing in the routing instance object, router is the attribute method containing routing in the routing instance object, router is the property method containing routing in the routing instance object, and route is the current browsing access url routing confidence object.

* VueRouter instance properties

App configures the Vue root instance of the current router

The mode "hash" | "history" currently used by mode Router

Route information object corresponding to the current route of currentRoute

VueRouter instance method

Router.push (string | location)

Programmer navigates to the specified route

Home page followers | recommended export default {methods: {gotoRecommend () {/ / this.$router.push ("/ home/recommend"); this.$router.push ({path: "/ home/recommend", query: {wd:1,offset:0}})},},}; router.replace (string | location)

Programmer replaces the current route to navigate to the new route

Home page followers | export default {methods: {gotoRecommend () {/ / this.$router.replace ("/ home/recommend"); this.$router.replace ({path: "/ home/recommend", query: {wd:1,offset:0}})},},}; router.go (Int number)

The programmer moves forward and backward number bars from the location of the current routing history stack

This.$router.go (3) / / forward 3 this.$router.go (- 1) from the location of the current route history stack / / back 1 this.$router.go (0) / / force refresh page from the location of the current route history stack

Note that when the current forward / backward number is greater than the length of the instance routing history stack, it will advance to the last line or fall back to the first, but it is not recommended that this will cause performance problems and cause page stutters.

Router.back ()

The programmer retreats 1 bar from the location of the current route history stack

This.$router.back () / / is equivalent to this.$router.go (- 1) router.forward ()

The programmer advances 1 from the location of the current routing history stack

This.$router.forward () / / is equivalent to this.$router.go (1) routing lazy loading

When writing a single page application with vue.js, the packaged JavaScript package will be very large, which will affect the page loading. We can use the lazy loading of routes to optimize this problem. When we use a certain route, we will load the corresponding components, which will be more efficient.

Do not use lazy loading

The components are introduced first and loaded in advance. Then whether it is used or not, it already exists.

Import Vue from 'vue'import VueRouter from' vue-router'import Home from'.. / views/Home.vue'Vue.use (VueRouter) const routes = [{path:'/', name: 'Home', component: Home},] const router = new VueRouter ({routes}) export default router uses lazy loading

Load the corresponding component only when the route is used

Import Vue from 'vue'import VueRouter from' vue-router'Vue.use (VueRouter) const routes = [{path:'/ mock', name: 'Mock', / / route level code-splitting / / this generates a separate chunk (about.[ hash] .js) for this route / / which is lazy-loaded when the route is visited. Component: () = > import (/ * webpackChunkName: "about" * /'.. / views/Mock.vue')}] const router = new VueRouter ({routes}) export default routerhistory mode and hash mode

Vue-router default hash mode-uses URL's hash to simulate a full URL, so when the URL changes, the page does not reload.

If you don't want an ugly hash, you can use the routed history mode, which takes full advantage of history.pushState API to complete the URL jump without reloading the page.

History mode

History-takes advantage of the new pushState () and replaceState () methods in HTML5 History Interface. (specific browser support is required) these two methods are applied to the history stack of the browser. Based on the existing back, forward and go (the method can be viewed in the instance method of Router), they provide the function to modify the history. It's just that when they make changes, although the current URL is changed, the browser does not immediately send a request to the back end.

Manual settin

Effect.

Hash mode

Hash-the # symbol in the address bar URL (this hash is not a hash operation in cryptography). For example, the value of this URL: http://localhost:8081/#/form hash is # / form. Its feature is that although hash appears in the URL, it is not included in the HTTP request and has no impact on the back end at all, so changing the hash will not reload the page.

Routing guard

Global routing guard

Router.beforeEach front guard

* router.beforeResolve front guard

* router.afterEach rear guard

Situation one

In projects developed with vue-router, switching between different routes generally unloads the outgoing routing components and mounts the incoming routing components.

In this case, we can perform some logical operations on the page through the declaration cycle of vue. However, in some cases, if the application reduces the uninstall frequency or saves the activity of leaving the component in order to improve the user experience, the switch of the route after wrapping the router-view with the keep-alive component will uninstall the leaving component. At this point, if your component needs to do some operations to modify its own data DOM programming when routing in or out, you can no longer rely on the life cycle of vue. In this case, use the routing guard within the component.

The beforeRouteEnter routing component is about to enter

BeforeRouteUpdate (2.2new) routing components will be updated-> / music/10086 / music/10010

The beforeRouteLeave routing component is leaving

Export default {props: ['id'], data () {return {musicUrl:''}}, beforeRouteEnter (to, from, next) {/ / call / / No before rendering the corresponding route for this component by confirm! Yes! Get component instance `this` / / because before the guard executes, the component instance has not been created console.log (undefined)}, beforeRouteUpdate (to, from, next) {/ / the current route changes, but the component is called / / for example, for a path / foo/:id with dynamic parameters, when it jumps between / foo/1 and / foo/2 / / because the same Foo component is rendered, the component instance is reused. And this hook will be called in this case. / / can access component instance `this`}, beforeRouteLeave (to, from, next) {/ / call / / access component instance `this`} when navigating away from the corresponding route of the component

Note that the routing guard methods exclusive to components all contain three parameters, to from next.

To: the destination route information object of the location route navigation jump

From: location which routing information object does the routing navigation jump from ()

Next: function whether this method allows this route to jump

Next () / / allow route to jump next (true) / / allow route to jump next (false) / / do not allow route to jump next ('/') / next ({path:'/'}) / / to a different address. The current navigation is interrupted and a new navigation is carried out. You can pass objects anywhere to next, and allow you to set options such as replace: true, name: 'home'. / / Note that only the next method of beforeRouteEnter can accept a callback function. / / this callback function accepts the current routing component instance object as a parameter. We can operate on the current component beforeRouteEnter (to, from, next) {console.log (to, from) console.log ('component is about to enter, this is component instance does not exist yet'). This) next (vm = > {fetch (`/ song/url?id=$ {vm.id}`). Then (res) = > res.json (). Then (({data}) = > {/ / in real development, it is necessary to determine whether the data request is successful or not console.log (data [0]) / / assign the data of the song to data vm.musicUrl = data [0]? .url});}) / / allow routing to jump} case 2

In projects developed with vue-router, switching between different routes generally unloads the outgoing routing components and mounts the incoming routing components.

In this case, we can perform some logical operations on the page through the declaration cycle of vue. However, if in some cases the application reduces the uninstall frequency or saves the activity of leaving the component in order to improve the user experience, use the keep-alive component to package the switch of the router-view route, it will uninstall the leaving component at this time, if your component needs to perform some operations when the route enters or leaves, there is no need to modify the state of the component itself, just to determine whether the route is allowed to jump and so on. In this case, use the routing exclusive guard.

BeforeEnter (to, from, next) triggers const router = new VueRouter when the route is about to navigate to the current route ({routes: [{path:'/ foo', component: Foo, beforeEnter: (to, from, next) = > {/ /.}}]})

Case login authentication route exclusive guard configuration

Const routes = [{path:'/', component: Home}, {path:'/ discover', component: () = > import ('.. / views/Discover')}, {path:'/ mine', component: () = > import ('.. / views/Mine'), / / route exclusive guard beforeEnter (to, from) Next) {/ / because the guard does not have any DOM operations or reads and writes the state of the component / / such a guard can be used as a routing exclusive guard / / the correct practice is stored in cookie storage if (localStorage.getItem ("user")) {next () } else {/ / there is no this here. Next receives a callback function, jumps / / in the callback function to enter the personal page, and then redirects to login from the personal page. This may result in some unnecessary bug / / next ((vm) = > {/ / vm.$router.replace ('/ landr') / /}) Next ({name:'login',params: {to}}) / / prevent this jump, navigate directly to the specified route}, {path:'/ landr', / / loginanregister component: () = > import ('.. / views/loginanregister/LoginAndRegister'), children: [{name:'login', path: 'login' Component: () = > import ('.. / views/loginanregister/Login')}, {path: 'register', component: () = > import ('.. / views/loginanregister/Register')}}] case 3

Global routing gatekeeper, when multiple routes in an application need to be judged by the same logic, and there is no need to directly manipulate the component DOM or the state of the component in the logical operation, you can use the global routing gatekeeper (the most common application of the global guardian is login verification)

BeforeEach (to,from,next) Global Front Guard

Import Vue from 'vue'import Router from' vue-router'import Home from'.. / views/Home'Vue.use (Router) const routes = [{path:'/', name: 'Home', component: Home}, {path:' / discover', name: 'Discover', component: () = > import ('.. / views/Discover')} {path:'/ mine', name: 'Mine', component: () = > import ('.. / views/Mine'),}, {path:'/ landr', / / loginanregister component: () = > import ('.. / views/loginanregister/LoginAndRegister'), children: [{name: 'login' Path: 'login', component: () = > import ('.. / views/loginanregister/Login')}, {path: 'register', component: () = > import ('.. / views/loginanregister/Register')}}] const router = new Router ({routes) LinkExactActiveClass: 'active'}) / / the global guard of the route will call this guard / / the global route guard is also the most suitable place for login verification in the Vue router application, router.beforeEach ((to, from) Next) = > {if (to.name = "Mine" | | to.name = "Discover") {/ / because the guard does not have any DOM operations or reads and writes the state of the component / / such a guard can be used as a routing exclusive guard / / the correct practice is stored in if (localStorage.getItem ("user")) {next () in cookie storage. } else {/ / there is no this here. Next receives a callback function, jumps / / in the callback function to enter the personal page, and then redirects to login from the personal page. This may result in some unnecessary bug / / next ((vm) = > {/ / vm.$router.replace ('/ landr') / /}) Next ({name: 'login', params: {to}); / / prevent this jump and navigate directly to the specified route}} else {next ()}) export default router

Router.beforeResolve (to,from,next) Global Front Guard, after beforeEach triggers

Router.afterEach (to, from) global rear guard, which is triggered when the guard route has left. The guard does not have next, and the next function does not change the navigation itself.

Thank you for your reading, the above is the content of "what is the routes configuration of Vue-Router". After the study of this article, I believe you have a deeper understanding of what the routes configuration of Vue-Router is, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report