Summary review
- The interviewer is more likely to be satisfied
- 10 differences between arrow functions and normal functions
- HTML blank Chinese character placeholder
- I want to learn more about how to judge arrays
- HTML Email preparation
1. Set multiple “path parameters”
2. Respond to route parameter changes
For reusable components (only with route parameters changed), the lifecycle function hooks are not called.
watch: {
'$route'(to, from) {// Respond to routing changes... }}Copy the code
beforeRouteUpdate (to, from, next) {
// react to route changes...
// don't forget to call next() }Copy the code
3. Route matching
{// will match all paths:The '*'} {// will match any path starting with '/user-' :'/user-*'
}
Copy the code
When using wildcard routes, ensure that the order of routes is correct, that is, routes containing wildcards should be placed last. The route {path: ‘*’} is usually used for client 404 errors. If you use History mode, make sure your server is configured correctly. When a wildcard is used, $route.params automatically adds a parameter named pathMatch. It contains parts of the URL that are matched by wildcards:
// give a route {path:'/user-*' }
this.$router.push('/user-admin')
this.$route.params.pathMatch // 'admin'// give a route {path:The '*' }
this.$router.push('/non-existing')
this.$route.params.pathMatch // '/non-existing'
Copy the code
4. Advanced matching mode
// The named parameter must have one"Single character"[A-zA-Z09] //? Optional {path:'/optional-params/:foo? '} // Foo can be set or not set to <router-link to="/optional-params">/optional-params</router-link>
<router-link to="/optional-params/foo">/optional-params/foo</router-link> // zero or more parameters {path:'/optional-params/*' }
<router-link to="/number"> No parameter </router-link> <router-link to="/number/foo000"> one parameter </router-link> <router-link to="/number/foo111/fff222"</router-link> // One or more parameters {path:'/optional-params/:foo+' }
<router-link to="/number/foo"> one parameter </router-link> <router-link to="/number/foo/foo111/fff222"> Multiple parameters </router-link> // custom matching parameters // Can provide a custom regexp for all parameters, which will override the default value ([^\/]+) {path:'/optional-params/:id(\\d+)' }
{ path: '/optional-params/(foo/)? bar' }
Copy the code
5. Match priorities
Sometimes, a path may match multiple routes. In this case, the matching priorities are defined in the order that routes are defined first.
The second and third arguments to push and replace
In 2.2.0+, it is optional to provide onComplete and onAbort callbacks as the second and third arguments in router.push or router.replace. These callbacks will be called when the navigation completes successfully (after all the asynchronous hooks have been resolved) or terminates (navigation to the same route, or to a different route before the current navigation completes). In 3.1.0+, the second and third arguments can be omitted, and router.push or router.replace will return a Promise if promises are supported.
// Component 1 jumps component 2 // component 1 this.$router.push({ name: 'number' }, () => {
console.log('Component 1: onComplete Callback');
}, () => {
console.log('Component 1: onAbort callback'); }); // component 2 beforeRouteEnter(to, from, next) {console.log('Component 2: beforeRouteEnter');
next();
},
beforeCreate() {
console.log('Component 2: beforeCreate');
},
created() {
console.log('Component 2: Created');
}
Copy the code
// Component 2 jumps component 2 (without arguments) this.$router.push({ name: 'number'}, () => {
console.log('Component 2: onComplete Callback');
}, () => {
console.log('Component 2, self jump: onAbort callback');
});
Copy the code
// Component 2 jumps component 2 (with arguments) this.$router.push({ name: 'number', params: { foo: this.number}}, () => {
console.log('Component 2: onComplete Callback');
}, () => {
console.log('Component 2, self jump: onAbort callback');
});
Copy the code
7. Routing view
Named views come in handy when you want to show multiple views at the same time (sibling) instead of nesting them, such as creating a layout that has sidebar (side navigation) and main (main content) views. Instead of having a single exit, you can have multiple individually named views in the interface. If router-view does not have a name, it defaults to default.
<router-view class="view one"></router-view>
<router-view class="view two" name="a"></router-view>
<router-view class="view three" name="b"></router-view>
Copy the code
A view renders with one component, so multiple views require multiple components for the same route. Make sure to use the Components configuration correctly (with s) :
const router = new VueRouter({
routes: [
{
path: '/',
components: {
default: Foo,
a: Bar,
b: Baz
}
}
]
})
Copy the code
redirect
{ path: '/a', redirect: '/b' }
{ path: '/a', redirect: { name: 'foo' }}
{ path: '/a', redirect: to => {// the method receives the destination route as a parameter //returnRedirected string path/path object}}Copy the code
Note that the navigational guard is not applied to the jump route, but only to its target. In the following example, adding a beforeEach or beforeLeave guard to the/A route has no effect.
Decouple $route using props
Using $route in a component makes it highly coupled to its corresponding route, limiting its flexibility by limiting its use to certain urls.
// Router file // For routes that contain named views, you must add the 'props' option for each named view: {path:'/number/:name',
props: true, // Object mode props: {newsletterPopup:false} // Function mode props: (route) => ({query: route.parmas.name}) name:'number',
component: () => import( /* webpackChunkName: "number"* /'./views/Number.vue'} // Component fetchexport default{
props: ['name']}Copy the code
Global guard
- Router. beforeEach Global front-guard before entering a route.
- Router. BeforeResolve Global Resolution Guard added in 2.5.0. Called after the beforeRouteEnter call.
- AfterEach Global post-hook after entering a route.
// import router from'./router'// Global front-guard router. BeforeEach ((to, from, next) => {console.log()'beforeEach Global front-guard '); next(); }); Router.beforeresolve ((to, from, next) => {console.log()'beforeResolve Global parsing Guard '); next(); }); Router.aftereach ((to, from) => {console.log()'afterEach global afterguard ');
});
Copy the code
Route exclusive guard
- BeforeEnter Global front-guard before entering a route.
{
path: '/number/:name',
props: true,
name: 'number', // Route exclusive guard beforeEnter: (to, from, next) => {console.log()'beforeEnter Route exclusive guard ');
next();
},
component: () => import( /* webpackChunkName: "number"* /'./views/Number.vue')}Copy the code
12. Component internal guard
- beforeRouteEnter
- 2.2 new beforeRouteUpdate ()
- beforeRouteLeave
BeforeRouteEnter (to, from, next) {beforeRouteEnter(to, from, next) {beforeRouteEnter(to, from, next) {beforeRouteEnter(to, from, next) { Can!!!! Get component instance 'this' // Because the component instance has not been created before the guard executes console.log('beforeRouteEnter component entry guard '); next(); }, beforeRouteUpdate(to, from, next) {// Called when the current route changes, but the component is being reused. For example, for a path with dynamic parameters /foo/:id, jumping between /foo/1 and /foo/2, // Since the same Foo component will be rendered, the component instance will be reused. And the hook will be called in that case. // Access component instance 'this' console.log('beforeRouteUpdate update guard within component '); next(); }, beforeRouteLeave(to, from, next) {// Call when navigating away from the corresponding route of the component // Access component instance 'this' console.log('beforeRouteLeave component leaves guard ');
next();
}
Copy the code
// Component 1 jumps to component 2, which then jumps to component 2 itself
12, Guard next method
Next: Function: Be sure to call this method to resolve the hook. The execution depends on the call parameters of the next method.
- Next (): Goes to the next hook in the pipe. If all hooks are executed, the navigation state is confirmed.
- Next (false): interrupts current navigation. If the browser URL changes (either manually by the user or by the browser back button), the URL is reset to the address corresponding to the FROM route.
- Next (‘/’) or next({path: ‘/’}): jumps to a different address. The current navigation is interrupted and a new navigation is performed. You can pass any location object to next, and you can set options like replace: True, name: ‘home’, and any options used in router-link’s to prop or router.push.
- Next (error): (2.4.0+) If the argument passed to Next is an error instance, the navigation is terminated and the error is passed to the callback registered with router.onerror ().
13. Rolling behavior
With front-end routing, you want the page to roll to the top when switching to a new route, or to keep the original scrolling position, as if the page were being reloaded. Vue-router can do this, and better, by letting you customize how the page scrolls when switching routes.
Note: This feature is only available in browsers that support history.pushState.
// scrollBehavior(to, from, savedPosition) {if(savedPosition) {// When the browser presses the back/forward buttonreturn savedPosition
} else {
return{x: 0, y: 0}} behavior (to, from, savedPosition) {if (to.hash) {
return2.8.0 New scrollBehavior(to, from, savedPosition) {selector: to.hash}}return new Promise((resolve, reject) => {
setTimeout(() => {
resolve({ x: 0, y: 0 })
}, 500)
})
}
Copy the code