How Do You Know You Should Relace Your Router
If yous are using Vue, the odds are you will need to deal with the Vue router. Let's go through all the common utilise-cases you will need! 👌
In this tutorial, nosotros volition cover the about essential router concepts likewise equally more avant-garde patterns such as guarded routes & animated routes.
Are you ready? Let's do this! 💪
Overview
Let's have a wait at the bigger motion picture commencement then dig deeper.
Project construction
I accept created a small vue projection to demonstrate unlike functionalities of the Vue Router. The project has a standard setup using the vue-cli.
├── README.md ├── babel.config.js ├── package.json ├── postcss.config.js ├── public │ ├── favicon.ico │ └── index.html ├── src │ ├── App.vue │ ├── assets │ │ └── logo.png │ ├── components │ │ └── HelloWorld.vue │ ├── primary.js │ ├── router.js │ └── views │ ├── Blithe.vue │ ├── Dynamic.vue │ ├── Guarded.vue │ ├── Home.vue │ ├── LazyLoaded.vue │ ├── Login.vue │ ├── Nested.vue │ └── WithProps.vue └── yarn.lock
We will be dealing mostly with the router.js but also different views.
Here is how the master router configurations look like:
import Vue from 'vue' ; import Router from 'vue-router' ; // All the views import Home from './views/Home.vue' ; import Nested from './views/Nested.vue' ; import Blithe from './views/Animated.vue' ; import Dynamic from './views/Dynamic.vue' ; import Guarded from './views/Guarded.vue' ; import Login from './views/Login.vue' ; import WithProps from './views/WithProps.vue' ; Vue. use (Router) ; consign default new Router ( { mode: 'history' , routes: [ { path: '/' , proper name: 'home' , component: Home, children: [ { name: 'nested-home' , path: 'nested' , component: Nested } ] } , { path: '/blithe' , component: Animated } , { path: '/dynamic/:id' , component: Dynamic } , { path: '/login' , component: Login } , { path: '/very-secure' , component: Guarded, beforeEnter : ( to, from , next ) => { let isAuthenticated; attempt { isAuthenticated = sessionStorage. getItem ( 'authenticated' ) ; } catch (error) { render next ( { path: '/login' } ) ; } return isAuthenticated ? next ( ) : next ( { path: '/login' } ) ; } } , { path: '/with-props' , component: WithProps, props: { newsletterPopup: true } } , { path: '/lazy-loaded' , name: 'lazyLoaded' , // route level code-splitting // this generates a separate chunk (lazyLoaded.[hash].js) for this route // which is lazy-loaded when the route is visited. component : ( ) => import ( /* webpackChunkName: "lazyLoaded" */ './views/LazyLoaded.vue' ) } ] } ) ;
Here is how we add the router when we are bootstraping our Vue app:
// src/master.js import Vue from 'vue' ; import App from './App.vue' ; import router from './router' ; new Vue ( { router, render : h => h (App) } ) . $mount ( '#app' ) ;
Now let's start to dig deeper and find out what does each part of these router configurations actually do. 🧐
Essentials
Using props
Example route-config:
// src/router.js { path: "/with-props" , component: WithProps, props: { newsletterPopup: true } }
A unproblematic view that gets props from the router:
// src/views/WithProps.vue <template> <div course = "home" > <h1>This is a view with props coming from the router! < /h1> <h2>Look at that - { { $props.newsletterPopup } } < /h2> < /div> < /template> <script> export default { props: { newsletterPopup: Boolean } } ; < /script>
You might have noticed that some of these routes have names divers. So how do these piece of work y'all wonder?
Named routes
A road proper noun provides an culling way to navigate to routes without relying on its path.
Instance route-config:
// src/router.js { path: "/" , component: Dwelling, children: [ { proper name: "nested-home" , path: "nested" , component: Nested } ] }
Here is how you can apply it in a router-link
<router-link :to = "{ name: 'nested-home' }" > Nested </router-link > |
Yous might be thinking to yourself..."huh, router-link? 😕"
router-link
The router-link helps you with navigation, its like anchor links merely with super powers.
Under the hood, information technology renders an ballast tag with correct href. Also, the router-link component gets automatically CSS classes when the target route is active.
It is considered a best-do to stick to router-link over regular anchor links.
Want to know more? Yous can dig deeper here.
You accept accept noticed this router-view thing!
router-view
In unproblematic terms, this the placeholder that gets replaced dynamically with the component that matches your route.
<router-view > </router-view >
Here the official description from the Vue docs:
The router-view component is a functional component that renders the matched component for the given path.
Components rendered in router-view can also contain its own router-view, which will return components for nested paths.
Any non-name props will be passed along to the rendered component, however almost of the time the per-road data is contained in the road's params.
Side by side, lets talk about nested routes...
Nested routes
Got a utilize-instance where you demand to nest routes? Piece of cake!
Yous tin can define children for the route.
Example route-config:
// src/router.js { path: "/" , component: Dwelling house, children: [ { name: "nested-home" , path: "nested" , component: Nested } ] }
Here is a view that has another nested route, hence the router-view
// src/views/Habitation.vue <template> <div grade = "domicile" > <img alt= "Vue logo" src= "../avails/logo.png" / > <HelloWorld msg= "Welcome to Your Vue.js App" / > <router-view / > < /div> < /template> <script> // @ is an alias to /src import HelloWorld from "@/components/HelloWorld.vue" ; export default { name: "home" , components: { HelloWorld } } ; < /script>
And the Nested view itself:
// src/views/Nested.vue <template> <div form = "about" > <h1>This is a nested view, Helloww! < /h1> < /div> < /template>
What about dynamic URL segments? If I have for example user IDs or a dynamic field of some sort?
Dynamic routing & Router param
Case of a route-config with dynamic segment :id
// src/router.js { path: "/dynamic/:id" , component: Dynamic }
Yous tin access the dynamic param in your component similar this:
// src/views/Dynamic.vue <template> <div> <h1>This is a very dynamic page, here is the id: < /h1> <h2 class = "highlight" > { { $route.params.id } } < /h2> <span>Its nigh like magic right? < /bridge> < /div> < /template> <style lang= "scss" scoped> .highlight { font-weight: bold; } < /style>
This is a proficient place to have a break! what about standing upward & stretching ? Go for it! I will exist here when yous come up back. 👍
Advanced
Ok at present that you know all the basics, allow'south have a look into the more advanced stuff.
Road guards
Here is how you can create protected routes that but authenticated users are allowed to see:
// src/router.js { path: "/login" , component: Login } , { path: "/very-secure" , component: Guarded, beforeEnter : ( to, from , adjacent ) => { let isAuthenticated; try { isAuthenticated = sessionStorage. getItem ( "authenticated" ) ; } catch (error) { return side by side ( { path: "/login" } ) ; } return isAuthenticated ? side by side ( ) : next ( { path: "/login" } ) ; } }
// src/views/Guarded.vue <template> <div form = "about" > <h1>This is a nested view, Helloww! < /h1> < /div> < /template>
// src/App.vue methods: { authenticate ( ) { sessionStorage. setItem ( "authenticated" , truthful ) ; } , logout ( ) { sessionStorage. removeItem ( "authenticated" ) ; } }
Keep in mind that this is but a simple case, yous might want to add more layers of checks in real-world applications. 😁
Wild card routes
Here is how you tin can add a wild card road to grab unknown routes.
{ // will match everything path: '*' ; component: NotFound; }
Y'all can use this technique to display a "Not Found 404" page. 💯
Watch road
What if you want to react to route changes? You tin can add a specific watcher to the $route object.
<script> export default { watch: { $route ( to, from ) { panel. log ( "to" , to) ; console. log ( "from" , from ) ; // react to route changes... } } } ; < /script>
Since we are at it, let'south talk well-nigh the route object.
The route object
Here is how the route object looks like :
interface RouteConfig = { path: string, component? : Component, name? : string, // for named routes components? : { [name: string] : Component } , // for named views redirect? : string | Location | Function, props? : boolean | Object | Function, alias? : string | Array<string> , children? : Array<RouteConfig> , // for nested routes beforeEnter? : ( to: Road, from : Road, side by side: Function ) => void , meta? : any, // 2.6.0+ caseSensitive? : boolean, // utilize case sensitive match? (default: false) pathToRegexpOptions? : Object // path-to-regexp options for compiling regex }
Desire to know more than? Check out the docs.
Do you lot happen to accept a bit more special use-cases? Allow's check how you lot tin can use the router options.
Router options
You lot can customize the router to your taste.
Here are some of the config options when initializing the router.
// src/router.js new Router ( { mode: 'history' , // the router mode routes: [ // Routes go here ] , base: '/' , // The base URL of the app linkActiveClass: 'router-link-active' , // <router-link> default active class linkExactActiveClass: 'router-link-verbal-active' , // <router-link> default active class for exact matches scrollBehavior ( to, from , savedPosition ) { // native-similar behavior when navigating with dorsum/forward buttons if (savedPosition) { return savedPosition } else { return { x: 0 , y: 0 } } }‚ parseQuery : q => q, // custom query string parse fallback: truthful , // whether the router should fallback to hash fashion } ) ;
You can dig deeper by reading the documentation:
- Router construction options.
- Ringlet beliefs
I know this has been a long tutorial, stay with me we are nigh done! 😌
Router transition
Want to add transitions effects to your routed component?
Adding elementary transitions in Vue is easy, just wrap your components inside the transition component.
// src/views/Animated.vue <template> <transition name= "fade" > <div> <h1>This is a animated page, it fades abroad slowly... < /h1> < /div> < /transition> < /template> <fashion lang= "scss" scoped> .fade-enter-active, .fade-get out-active { transition: opacity twos; } .fade-enter, .fade-exit-to { /* .fade-leave-active below version 2.ane.8 */ opacity: 0 ; } < /style>
You can read more than near Vue transitions & animations here.
Lazy-loading routes
Lazy-loading is a useful technique to increase the performance of your application. Here is an instance:
// src/router.js { path: "/lazy-loaded" , proper name: "lazyLoaded" , // route level code-splitting // this generates a separate chunk (lazyLoaded.[hash].js) for this route // which is lazy-loaded when the road is visited. component : ( ) => import ( /* webpackChunkName: "lazyLoaded" */ "./views/LazyLoaded.vue" ) }
// src/views/LazyLoaded.vue <template> <h1>This is a lazy-loaded view. Performance baby! < /h1> < /template>
This style, yous tin lazy-load routes only when they are needed. Merely use the dynamic import syntax (equally y'all tin run into in the src/router.js snippet) and you are good to go.
Navigation Resolution Flow
The router has different hooks that are executed in a specific guild.
Understanding the sequence of these hooks is helpful. This manner you tin can ensure that your logic is at the right place at the right fourth dimension.
Here is a, poorly drawn, diagram that explains the execution order of the router hooks:
A couple of employ cases of the router hooks:
- Want to have globally guarded routes? Hook number 2 beforeEach that runs globally might be your all-time option.
- Want to add component-specific router logic? Have a look at the hook number five beforeRouteEnter.
That is it, now you are a Vue router guru! ✋
Enjoyed the article? Share the summary thread on twitter.
Source: https://nordschool.com/vue-router/
0 Response to "How Do You Know You Should Relace Your Router"
Postar um comentário