vue-router Flashcards
Install and setup
npm install vue-router
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
Research Lazy Loding vue-router
``
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 ofto
.
router-link
to
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
router-link
replace
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
router-link
append
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
router-link
tag
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"
router-link
active-class
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"
router-link
exact
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 /
router-link
event
Specify the event(s) that can trigger the link navigation.
- type:
string | Array
- default:
'click'
router-link
exact-active-class
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"
router-link
Active Class to Outer Element
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.
router-view
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 a
router-view
has a name, it’ll render the component with the corresponding name in the matched route record’scomponent
option. - Use the
components
option in aRouteConfig
to define multiple components to render to. - A
router-view
without a name will be given the namedefault
.
Router Constructor Options
routes
mode
base
linkActiveClass
linkExactActiveClass
scrollBehavior
-
parseQuery
/stringifyQuery
fallback
Router Constructor Options
routes
- Dynamic Segments
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 usebeforeRouteUpdate
- 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'}
Router Constructor Options
routes
- Nested Routes
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}
Programmatic Navigation
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 usepath
, leave out a param, and then define it in aparams
option.- Otherwise, can use
name
option withparams
.
- Otherwise, can use
- All same rules as for
-
onComplete
andonAbort
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 entryn
entries away from the current one.- Will silently fail if out of range
Router Constructor Options
routes
- Redirect
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 pathb
-
- 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 aroute
object
-
- retrun a string of a path, or a
route
object
- Have a catchall for unknown pages
{ path: '*', redirect: '/' }
Router Constructor Options
routes
- Alias
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 ComponentA
-
{ 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
-
Router Constructor Options
routes
- Props
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-view
s, must defineprops
as an object for each named viewprops: {default: true, sidebar: false}
- When
props
is set as an object for single view (nested objects for multiple named views), then theprops
object will be set as-is, useful for static propsprops: {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 normalroute
object
HTML5 History Mode
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 }
Navigation Guards
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 thebeforeRouteUpdate
in-component guard
- Must either watch the
- 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
- the target
-
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
- abort the current navigation, if browser URL was changed (manually or back button), it’ll be reset to the
-
next('/')
ornext({path: '/'})
- redirect to a different location. Current navigation and new one will be started
-
next(Error)
- if argument to
next
is of typeError
, navigation will be aborted and the error will be passed to callbacks registered viarouter.onError()
- if argument to
- Always call
next
function, otherwise the hook will never be resolve
-