vue-router Flashcards

1
Q

Install and setup

A

npm install vue-router

import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)

Research Lazy Loding vue-router

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

``

A

The component for enabling user navigation that specifies the target location with the to prop.

  • The link automatically gets an active class when target route is active.
  • Works the same way in both HTML5 history mode and hash mode. Router falls back to hash mode automatically in IE9.
  • In HTML5 history mode, router-link will intercept the click event so that the browser doesn’t try to reload the page.
  • When using the base option in HTML5 history mode, you don’t need to include it in the URLs of to.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

router-link

to

A

Denotes target route of the link. When clicked, value of to will be passed to router.push() internally. Value can be a string or a location.

  • type: string | location
  • required

to can contain:

to="home" // literal string

:to="'home'" //js expressions using v-bind

:to="{path: home}" // use path key denote path

:to="{name: 'user', params: { userId: 1833}}" // name route with route params

:to="{path: 'register', query: {source: 'chrome'}}" //path with query params

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

router-link

replace

A

Setting replace prop will call router.replace() instead of router.push() when clicked, so the navigation will not leave a history record.

  • type: boolean
  • default: false

:to="{path: 'register', query: {source: 'chrome'}}" replace //replaced path with query params

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

router-link

append

A

Setting append prop always appends the relative path to the current path. The to-be-appended relative path must be a child of another path to work. Must not contain a / before it either.

  • type: boolean
  • default: false

:to="{path: home}" append
adds home to /current/path/ => /current/path/home

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

router-link

tag

A

If we want to render as some tag other than the default tag, such as ``. Will still listen for click events for navigation.

  • type: string
  • default: a

:to="{path: home}" tag="li"

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

router-link

active-class

A

Configure the active CSS class applied when the link is active. The default value can be configured globally with the linkActiveClass router constructor option.

  • type: string
  • default: router-link-active

:to="{path: home}" active-class="active-page"

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

router-link

exact

A

Default active class matching behavior is inclusive matching . In the case of to="/users/evan", every path that starts with /users/evan/ trigger the base path of /users/evan to have an active class. To prevent this, put exact on the path that you only want to be active when it is exactly matched.

  • type: boolean
  • default: false

`` // the class will only be active at /

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

router-link

event

A

Specify the event(s) that can trigger the link navigation.

  • type: string | Array
  • default: 'click'
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

router-link

exact-active-class

A

Specify the active applied CSS class when the link is active with an exact match. The default can be configured globally via the linkExactActiveClass router constructor option.

  • type: string
  • default: "router-link-exact-active"
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

router-link

Active Class to Outer Element

A

Render outer element using and wrap the raw inside.

The outer rendered gets the active class, and the inner will be the actual link with the correct href applied.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

router-view

A

Functional component that renders the matched component for the given path.

  • Components rendered within can contain their own (s), as default views or named views
  • When using with and , make sure to use on the outside.
  • You can pass data with props but better to use per-route data

name prop:

  • type: string
  • default: "default"

Named views:

  • When arouter-view has a name, it’ll render the component with the corresponding name in the matched route record’s component option.
  • Use the components option in a RouteConfig to define multiple components to render to.
  • A router-view without a name will be given the name default.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Router Constructor Options

A
  • routes
  • mode
  • base
  • linkActiveClass
  • linkExactActiveClass
  • scrollBehavior
  • parseQuery/stringifyQuery
  • fallback
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Router Constructor Options

routes - Dynamic Segments

A

Dynamic Segments

  • A dynamic segment is denoted by a colon :
  • The value of dynamic segments will be exposed as this.$route.params in all components
  • When changing paths with both paths having the same component, the same component instance will be reused, thus not firing the typical lifecycle hooks.
  • To react to params changes in same component, watch the $route object, or use beforeRouteUpdate
  • If more than one RouteConfig matches, the earliest one in order of definition is used.
  • Params can be made optional by adding ?
    • {path: '/optional-param/foo?'}
  • Param can be followed by a regex pattern - will only match if id is all all numbers
    • {path: '/users/:id(\\d+)'}
  • Asterick can match anything
    • {path: '/test-site/*'}
  • Can make part of the path optional by wrapping in parens and ending adding ?
    • {path: '/users/(admin/)?:id'}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Router Constructor Options

routes - Nested Routes

A

Nested Routes

  • children option is just another array of RouteConfig objects
  • To match a base route that has children, add a primary child RouteConfig that has a path value of ''
    • { path: '', component: UserHome}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Programmatic Navigation

A

Can access the router inside a component via this.$router

  • To navigate to a page, use router.push(location, onComplete?, onAbort?)
  • router.push() is called when using
  • Must use ES6 template syntax if using path key to navigate, cannot use path, leave out a param, and then define it in a params option.
    • Otherwise, can use name option with params.
  • All same rules as for
  • onComplete and onAbort are called upon successful navigation, otherwise aborted navigation (navigated to same route or to a different route before current navigation finished)
  • Navigate without pushing a new history entry: router.replace(location, onComplete?, onAbort?)
  • router.go(n) to navigate to a history entry n entries away from the current one.
    • Will silently fail if out of range
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

Router Constructor Options

routes - Redirect

A

Redirection is done in the routes config.

  • To redirect to a path:
    • redirect: "/b" // absolute path to redirect to /b
    • redirect: "b" // relative path to redirect to sibling path b
  • Redirect to a named route:
    • redirect: {name: "about"} // redirect to named route
  • Dynamic Redirect using a function:
    • redirect: to => {}
    • Target route to is the available parameter
      • to is a route object
    • retrun a string of a path, or a route object
  • Have a catchall for unknown pages
    • { path: '*', redirect: '/' }
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

Router Constructor Options

routes - Alias

A

When a user visits an alias, the url will remain as that url alias, but will display the actual route that the alias is defined on, which will be a different path.

  • To make a basic alias, URL will remain /b but display Component A
    • { path: '/a', component: A, alias: '/b' } // alias of an absolute path
  • Can use relative alias paths
    • { path: 'profile', component: UserProfile, alias: 'profile-beta' }
    • If a child of /home path, will match /home/profile-beta as an alias, and /home/profile as main path
  • Can assign multiple aliases to a path
    • alias: ['/test-profile', 'profile-beta']
  • Default child route with empty string alias
    • { path: 'default', component: Default, alias: '' }
  • Nested aliases will still work
    • /home/profile-beta/edit alias will be displayed, but will be rendering component as if /home/profile/edit was used
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

Router Constructor Options

routes - Props

A

Poor practice to use $route in components as it creates a tight coupling between the component and route. Use props option instead.

  • Pass in all dynamic segments as props
    • {path: '/user/:id', component: User, props: true}
  • If using named views with multiple components and router-views, must define props as an object for each named view
    • props: {default: true, sidebar: false}
  • When props is set as an object for single view (nested objects for multiple named views), then the props object will be set as-is, useful for static props
    • props: {newsletterPopup: false}
  • Can create a function that returns an object to pass to the component as props
    • props: (route) => ({name: route.query.q})
    • route parameter is same as normal route object
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

HTML5 History Mode

A

By default, vue-router is in hash mode. Uses hashes so that pages aren’t reloaded by the server.

  • We can use router’s history mode which leverages history.pushState API to achieve URL navigation without a page reload
  • Need to add a catch-all fallback route to the server
  • Since server will no longer report 404’s because of the catch-all, we must do that in Vue
    • { path: '*', component: NotFoundComponent }
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

Navigation Guards

A

Navigations guards are used to guard navigations by either redirecting or cancelling it.

  • Can hook into the route navigation process globally, per-route, or in-component
  • Params and query changes will not trigger enter/leave navigation guards
    • Must either watch the $route object or use the beforeRouteUpdate in-component guard
  • Guards may be resolved asynchronously and navigation is considered pending until all hooks have been resolved
  • Every guard gets 3 arguments
    • to: Route
      • the target Route object being navigated to
    • from: Route
      • the current route being navigated away from
    • next: Function
      • this function must be called to resolve the hook
      • next()
        • move on to the next hook in the pipeline, if no more hooks, then navigation is confirmed
      • next(false)
        • abort the current navigation, if browser URL was changed (manually or back button), it’ll be reset to the from route
      • next('/') or next({path: '/'})
        • redirect to a different location. Current navigation and new one will be started
      • next(Error)
        • if argument to next is of type Error, navigation will be aborted and the error will be passed to callbacks registered via router.onError()
      • Always call next function, otherwise the hook will never be resolve
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

Navigation Guards

Global Guards

A

Global Before Guards

router.beforeEach

  • Register global before guards using router.beforeEach
    • router.beforeEach((to, from, next) => {})
  • These guards are called in creation order whenever a navigation is triggered

Global Resolve Guards

router.beforeResolve

  • Similar to router.beforeEach, but these will be called right before the navigation is confirmed, after all in-component guards and async route components are resolved.

Global After Hooks

router.afterEach

  • Unlike global guards, these hooks do not get a next function and cannot affect navigation
23
Q

Navigation Guards

Per-Route Guards

A

Define per-route guards directly within RouteConfig objects.

{path: '/home', component: Home, beforeEnter: (to, from, next) => {}}

These guards have the exact same signature as the global before guards.

24
Q

Navigation Guards

In-Component Guards

A

Can define route navigation guards inside route components

  • beforeRouteEnter(to, from, next)
    • Called before the route that renders this component is confirmed
    • Does not have access to this component instance because component would not have been created yet when this guard is called
    • Can access this component instance by passing a callback to next
      • Callback will be called when navigation is confirmed, and component instance will be passed to the callback as an argument
      • beforeRouteEnter(to, from, next) { next( vm => {}) }
  • beforeRouteUpdate(to, from, next)
    • Called when the route that renders this componet has changed, but the component is being reused in the new route.
    • Has access to this component instance
    • For /foo/:id, this hook will be called navigation from /foo/1 to /foo/2
  • beforeRouteLeave(to, from, next)
    • Called when the route that renders this component is about to be navigated away from.
    • Access to this component instance
    • Usually used to prevent user from leaving page with unsaved edits
    • Can cancel with next(false)
25
Q

Navigation Resolution Flow

A
  1. Navigation triggered
  2. Call beforeRouteLeave guards in deactivated components
  3. Call global beforeEach guards
  4. Call beforeRouteUpdate guards in reused components
  5. Call beforeEnter in route configs - global and per-route
  6. Resolve async route components
  7. Call beforeRouteEnter in activated components
  8. Call global beforeResolve guards
  9. Navigation Confirmed
  10. Call global afterEach hooks
  11. DOM updates triggered
  12. Call callbacks passed to next in beforeRouteEnter guards with instantiated instances
26
Q

Route Meta Fields

A

Can include meta fields in RouteRecord definitions.

{path: '/home', component: Home, meta: {needAuth: true}}

  • Since RouteRecords are nested, a matched route can match more than one RouteRecord
  • All matched RouteRecords are exposed as an $route.matched array
  • We can iterate over $route.matched to find out if any matched RouteRecords require auth, forcing us to check auth status

router.beforeEach((to, from, next) => { if (to.matched.some(record => record.meta.needAuth)) { // do something about it }}

27
Q

Transitions

A

router-view is a dynamic component, so all standard transition effects work the same way

` `

  • The above will cause the main to have the same transition applied for all inserted components since the main only appears in one place.
  • To have different transitions for different route components, take out surrounding the and instead make it the top-level element inside of the actual component template
  • To dynamically determine the transition to use, use a :name="transitionName" prop on `` at the top level of the component, watch $route (to, from) { // ... }, and assign name
    • more reliably, I would use beforeRouteLeave, to determine how the component should transition out
28
Q

Data Fetching

A

Fetching After Navigation

  • Perform navigation first, then fetch user data in incoming component’s lifecycle hooks
  • Display loading screen while being fetched
  • Create a fetchData() method, call it in created hook, and watch $route for changes and call fetchData() there as well
  • $route will only change once, since it’s entire object is switching to the new navigation process

Fetching Before Navigation

  • Fetch data before navigation in the route enter guard, and perform navigation after data has been fetched
  • Use a method setData() to set the fetched data to the component state
  • Use beforeRouteEnter on first component load (and the special callback passed to next to get a hold of the instance this when all other navigations are resolved) and pass the data to setData
  • Use beforeRouteUpdate upon component being reused to fetch new data, then passing it onto setData, immediately followed by next() to continue with navigation
29
Q

Scroll Behavior

A

Overview

  • Scroll behavior only works in HTML5 history mode
  • Provide the scrollBehavior instance when instantiating the VueRouter class
  • Arguments are to, from, and savedPosition
    • savedPosition can only be triggered if Back/Forward button were manually pressed
  • Can return either:
    • {x: number, y: number}
    • {selector: string, offset? : {x: number, y: number}}
  • If a falsy value or empty object is returned, no scrolling will happen

Usage

  • Should check if (savedPosition) { return savedPosition } first to see if it was a back forward command
  • Then check if (to.hash) { return {selector: to.has } to see if it was just an anchor change of the page
    • Can set offset of the element you’re scrolling to
  • Set meta field of routes as well and use to.matched.some() to see if any parent routes needs to be scrolled somewhere
30
Q

Route Constructor Options

routes

A

RouteConfig declaration

path: string;component?: Component; name? string; // named routescomponents?: { [name: String]: Component}; // for named viewsredirect?: string | Location | Function;props?: boolean | object | Function;alias?: string | Array;children?: Array; // for nested routesbeforeEnter?: {to: Route, from: Route, next: Function} => void;meta?: any;caseSensitive?: boolean; // defaulted to falsepathToRegexpOptions?: Object; // path-to-regexp options for compiling regex

31
Q

Route Constructor Options

mode

A

Configure the router mode

  • type: string
  • default: "hash" (in browser) | "abstract" (in Node.js)
  • history: requires HTML5 History API and server config
  • hash: uses the URL has for routing. Works in all Vue-supported browsers
  • abstract: works in all JS environments, server side. Will automatically be forced into this mode if no browser API is present
32
Q

Route Constructor Options

base

A

Base URL of the app. If entire SPA is served under /app, then base value should be "/app".

  • type: String
  • default: "/"
33
Q

Router Constructor Options

linkActiveClass

A

Globally configure `` default active class.

  • type: String
  • default: "router-link-active"
34
Q

Router Constructor Options

linkExactActiveClass

A

Globally configure `` default active class for exact matches.

  • type: String
  • default: "router-link-exact-active"
35
Q

Router Constructor Options

scrollBehavior

A

Configure scroll behavior when navigation to new route.

  • type: Function

Signature:

( to: Route, from: Route, savedPosition?: {x: number, y: number}) => {x: number, y: number} | {selector: string} | ?{}

36
Q

Router Constructor Options

parseQuery/stringifyQuery

A

Provide custom query string parse / stringify functions. Overrides the default.

  • type: Function
37
Q

Router Constructor Options

fallback

A

Controls whether router should fallback to hash mode when the browser does not support history.pushState.

  • type: boolean
  • default: true
  • Settings this to false essentially makes every router-link navigation a full page reload in IE9
  • This is useful when the app is server-rendered and needs to work in IE9, because a hash mode URL does not work with SSr.
38
Q

Router Instance - Properties

app

A

The root Vue instance the router was injected into.

  • type: Vue instance
39
Q

Router Instance - Properties

mode

A

The mode the router is using.

  • type: String
40
Q

Router Instance - Properties

currentRoute

A

The current route represented as a Route object

  • type: Route
41
Q

Router Instance - Methods

addRoutes

A

Dynamically add more routes to the router.

  • Argument must be an array using same route config format with the routes constructor option

router.addRoutes(routes)

42
Q

Router Instance - Methods

onError

A

Register a callback which will be called when an error occurs during navigation. For an error to be called, one of the following must happen:

  • Error is thrown synchronously in a route guard function
  • Error is caught and asynchronously handled by calling next(err) inside a route guard function
  • An error occurred when trying to resolve an async component that is required to render a route
43
Q

Router Instance Properties

A
  • router.app
  • router.mode
  • router.currentRoute
44
Q

Router Instance Methods

A
  • router.beforeEach(guard)
  • router.beforeResolve(guard)
  • router.afterEach(hook)
  • router.push(location, onComplete?, onAbort?)
  • router.replace(location, onComplete?, onAbort?)
  • router.go(n)
  • router.back()
  • router.forward()
  • router.getMatchedComponents(location?)
    • Return array of the component definition/constructor that’s matched by the provided location or current Route. Used server side for data prefetching
    • Research more
  • router.resolve(location, current?, append?)
  • router.addRoutes(routes)
    • Dynamically add more routes to the router. Argument must be an array using same route config format as in the routes constructor option
  • router.onReady(callback[, errorCallback])
    • Queues a callback to be called when router has completed initial navigation. It’s resolved all async enter hooks and async components that are associated with the initial route.
    • Useful on server side rendering
    • errorCallback will be called when initial navigation runs into an error, failed to resolve an async component
    • Research more
  • router.onError(callback)
45
Q

Router Instance - Methods

resolve

A

Reverse URL resolving. Given location in same format as ``, return object with the following resolved properties.

{ location: Location; route: Route; href: string;}

  • current is the current Route by default
  • append allows you to append the path to the current Route (as with router-link)
46
Q

Route Object

A

Route object represents the state of the current active route. Contains parsed information of the current URL and the route records matched by the URL.

  • Route object is immutable
  • Every successful navigation will result in a fresh new Route object
  • Can be found in multiple places
    • In components as this.$route
    • Inside $route watcher callbacks
    • Return value of calling router.match(location)
  • In navigation guards as the first two arguments
  • In scrollBehavior as the first two arguments
47
Q

Route Object - Properties

$route.path

A

String that equals the path of the current Route, always resolve as an absolute path.

  • Example: "/foo/bar"
  • type: String
48
Q

Route Object - Properties

$route.params

A

Object that contains key/value pairs of dynamic segments and star segments.

  • type: Object
  • If no params, the value will be empty object
  • Research star segments
49
Q

Route Object - Properties

$route.query

A

Object containing key/value paris of the query strings.

  • type: Object
  • example: /foot?user=1, we get $route.query.user == 1
  • If no query params, value will be empty object
50
Q

Route Object - Properties

$route.hash

A

Hash of the current Route (with the # if it has one). If no hash present, value will be an empty string.

  • type: String
51
Q

Route Object - Properties

$route.fullPath

A

Full resolved URL including query and hash.

52
Q

Route Object - Properties

$route.matched

A

An Array containing Route Records for all the nested path segments of the current route.

  • Route Records are the copies of the objects in the routes configuration Array (and in children Arrays)
  • type: Array
  • Array is in parent to child order
53
Q

Route Object - Properties

$route.name

A

The name of the current route, if it has one.

54
Q

Component Injections

A

Inject Properties

  • $router - the router instance
  • $route - the current active Route. Read-only but can be watched.

Enabled Options

  • beforeRouteEnter
  • beforeRouteUpdate
  • beforeRouteLeave