Vue Router based
Vue Router is used basically
-
Use in HTML
- use
router-link
Components navigate in HTML - By passing in
to
Attribute specified link <router-link>
The default is rendered as one<a>
The label
- use
-
Usage considerations in JavaScript
After the router is injected, the router can be accessed from any component through this.$router and the current route through this.$route
When the route corresponding to
is successfully matched, the class attribute is automatically set. Router-link-active
Dynamic Route Matching
Dynamic Path Parameters can be used in vue-router routing paths.
Dynamic path parameters are marked with colon:, such as path: ‘/user/: ID ‘. When a route is matched, the parameter value is set to this.$route.params, which can be used in each component
-
Responds to changes in routing parameters
When routing parameters are used, the original component instance is reused, and the component’s lifecycle hook is no longer invoked
If you want to react to changes in routing parameters when reusing components, you can monitor the $Route object using Watch or use the beforeRouteUpdate navigational guard
-
Capture all routes or 404 Not found routes
If you want to match any path, you can use the wildcard *, {path: ‘*’}
In general, routes with wildcards should be placed last; they are usually used for client 404 errors
When a wildcard is used, $route.params automatically adds a parameter named pathMatch, which contains the portion of the URL that is matched by the wildcard
Wildcards can be combined in path, for example {path: ‘/user-* ‘}
-
Advanced matching mode
Vue-router uses path-to-regexp as a path matching engine and supports multiple advanced matching modes
-
Matching priority
A path can match multiple routes, and the matched priorities are based on the route definition sequence. The earlier a route is defined, the higher the priority is
Embedded routines by
{router-view> is the top exit. It renders components matched by the highest level routes. The rendered components can also contain their own nested
The children configuration is used in the VueRouter argument, and the children matching component is rendered in the
where it is defined
Note: nested paths starting with/are treated as root paths; in other words, child paths in children do not need to start with a /
Programmatic navigation (programmatic routing navigation)
-
router.push(location, onComplete? , onAbort?)
Note: Inside the Vue instance, the routing instance can be accessed through $router, so this.$router.push can be called
The router.push method navigates to different urls and adds a new record to the history stack,
The router.push method can take a string path or an object that describes the address
Router.push ('home') // Object router.push({path: 'home'}) // Named router.push({name: 'user', params: {userId: Router.push ({path: 'register', query: {plan: 'private'}})Copy the code
Note: If path is provided, params is ignored. There are two ways to write params:
Router.push ({name: 'user', params: {userId: Router.push ({path: '/home/${userId}'}) {router.push({path: '/home/${userId}'});Copy the code
The onComplete and onAbort callbacks can be passed in as the second and third arguments
The onComplete callback is called after the navigation completes successfully (after all the asynchronous hooks have been resolved)
The onAbort callback function is called on termination (navigation to the same route, or to a different route before the current navigation is complete)
Note: If the destination is the same as the current route, only the route parameters change and you need to use beforeRouteUpdate to respond to the change
-
router.replace(location, onComplete? , onAbort?)
Similar to router.push, router.replace does not add a new record to history, but replaces the current history
-
router.go(n)
The router.go method takes an integer indicating how many steps forward or backward in the history
After routing
When creating a Router instance, you can name a route using the name attribute in the Routes configuration
Pass an object to the router-link property as shown in the following example:
<router-link :to="{ name: 'user', params: { userId: 123 }}">User</router-link>
Copy the code
Named view
If you need to render multiple views (that is, components) on a layout, you can use named views, specifying name in
to match components in components
If router-view does not have a name, it defaults to default
A view is rendered with one component, so multiple views require multiple components to render. The following is an example for configuring Componenets:
const router = new VueRouter({
routes: [
{
path: '/',
components: {
default: component1
name: component2
}
}
]
})
Copy the code
Redirects and aliases
-
redirect
Redirection is accomplished using the Routes configuration. The redirection target can be a path, named route, or a method to dynamically return the redirection target, as shown in the following example:
Const router = new VueRouter({routes: [// routes {path: '/a', redirect: '/b'} // Named routes {path: '/a', redirect: {name: 'ABC'}} // method receives target route as parameter, return redirects string path/path object {path: '/a', redirect: to => {return string path/path object}}]})Copy the code
-
The alias
For example, if the alias of /a is /b, when a user accesses /b, the URL remains /b, but the route matches /a, as shown in the following example:
const router = new VueRouter({ routes: [ { path: '/a', componenet: A, alias: '/b' } ] }) Copy the code
The ability of aliases is to map UI structures to arbitrary urls, that is, to control the URL jump rendering components, so that a UI structure can be accessed by multiple urls
Alias When multiple paths are specified, the alias can be followed by an array
Route component parameters are transmitted
Using $route on a component causes the component to be highly coupled to its route, so that the component can only be used on certain urls, which has a significant impact on component reusability. You can decouple the component from the route using props as shown in the following example:
const User = { props: ['id'], template: '<div>User {{ id }}</div>' } const router = new VueRouter({ routes: [ { path: '/user/:id', Component: user, props: true}, // If routes contain named views, add 'props' {path: '/user/:id', Component: { default: User, sidebar: Sidebar }, props: { default: true, sidebar: false } } ] })Copy the code
-
The Boolean model
If props is set to true, route.params will be set to the component property, which can be received by props
-
Object pattern
If props is an object, it is set as a component property as is. The component uses props to receive the corresponding data, which is useful when the props in routes is static
-
The function mode
If you create a function that returns props, you can convert arguments to another type, combine static values with route-based values, and so on, as shown in the following example
const router = new VueRouter({ routes: [ { path: '/search', componenet: SearchUser, props: route => ({ query: route.query.q }) } ] }) Copy the code
HTML 5 History pattern
Vue-router default hash mode — uses the HASH of the URL to simulate a complete URL. When the URL changes, the page will not be reloaded, and the hash mode will result in /# in the URL
You can use the history mode of the route, which makes full use of the history.pushState API to redirect urls without reloading the page. This can be done by setting the mode property to History
Problems of this model is the need to have the background configuration support, client applications because the application is a single page, if the background without the correct configuration, when a user in the browser directly input address access, 404, will return to there is a cover all increase on the server of candidate resources, if the URL can’t match any static resources, The same index.html page should be returned