Hook function of Vue [route navigation guard, keep-alive, life cycle hook]

Vue-Router navigation guard”:

Sometimes, we need to do some routing, such as the most common login privilege validation, when the user meets the conditions, let it enter the navigation, otherwise cancel the jump, and jump to the login page to let it login.
There are many ways to embed routing into the navigation process: global, single-route-exclusive, or component-level, preferring to read routing documents

vue-routerThere are three guardians in the whole world:

  1. router.beforeEach Global front guard before entering route
  2. router.beforeResolve The global resolution guard (2.5.0+) is called after the beforeRouteEnter call.
  3. router.afterEach The global post hook enters the route.

// main.js Entry fileImport router from'./router'; / / introduced routingRouter.beforeEach ((to, from, next) => {Next ();});Router.beforeResolve ((to, from, next) => {Next ();});Router.afterEach ((to, from) => {Console.log ('afterEach global post hook);});
to, from, next” have three parameters:

toAnd from are routing objects that are going to enter and leave, and routing objects are routing objects that are normally retrieved through this. $route.

next:Function This parameter is a function and must be called, otherwise it will not be able to enter the path (page blank).

  • next() Enter the route.

  • next(false): Cancel the access route, and reset the URL address to the from routing address (that is, the routing address to leave).

  • next The new route is skipping, the current navigation is interrupted, and a new navigation is resumed.

  We can jump like this: next ('path address) or next ({path:''}) or next ({name:''}).And allow options such as replace: true, name:'home', and so on.And the object options you use in router-link or router.push.

route exclusive guard

If you do not want to configure the guard globally, you can configure the guard for some routes separately.

    const router = new VueRouter({
      routes: [
        {
          path: '/foo',
          component: Foo,
          beforeEnter: (to, from, next) => { 
            // Parameters are used the same way, and the order of invocation is after the global guard, so they are not overwritten by the global guard/ /...}}]})

  1. beforeRouteEnter Before routing
  2. beforeRouteUpdate (2.2) When routing is multiplexed with the same component
  3. beforeRouteLeave When leaving the current routing

beforeRouteEnter (to, from, next) { // No calls after routing exclusive guards. Yes! Gets the component instance `this`, and the component instance has not been created yet.},BeforeRouteUpdate (to, from, next) {/ / the current routing changes, butWhen the component is reused, the component instance `this` can be accessed by calling.// For example, for a path / foo /: ID with dynamic parameters, when jumping between / foo / 1 and / foo / 2,/ / because it will render.The same Foo component, so component instances will be reused. And the hook will be called in this case.},BeforeRouteLeave (to, from, next) {/ / navigate away from the corresponding component.When called, the component instance `this` can be accessed.}
beforeRouteEnter access this

Because the hook is invoked before the component instance is created, the component instance this cannot be obtained and can be accessed by passing a callback to next

But the execution time of the callback is after mounted, so I don’t think it’s very meaningful to access this here. You can put it in create or mounted.

    beforeRouteEnter (to, from, next) {
    console.log('Call after routing exclusive guard.Next (VM => {)/ / through `vm` to access the component instance, the timing for `this` to perform callbacks is behind mounted.})}
beforeRouteLeave:

Navigation is called when it leaves the component’s corresponding route, and we use it to prevent users from leaving, such as not saving drafts, or destroying setInterval before the user leaves, so that the timer is still invoked after leaving.

    beforeRouteLeave (to, from , next) {
      if (Article saved) {Next (); / / allowed to leave or jump to other routes.} else {Next (false); / / cancel to leave}}

> routing hook function error capture

If we have an error in the hook function of the global guard/routing exclusive guard/component routing guard, we can catch:

    router.onError(callback => { 
    // 2.4.0New additions are not common.Console.log (callback,'callback');});

In the routing document there are more examples of methods: dynamic addition of routing and so on, interested in learning about.

router.beforeEach((to, from, next) => { if(Log in) {Next ()}else{Next ({name:'login'});}});

Logic seems to be right, but when we jump to login, because we’re still not logged in at this point, we’re going to jump to login and loop around, the page is always blank, so we need to change the judgment slightly.

    if(Log in || to. name =='login') {next ()}// or when you are about to go to the login page, you are allowed to route
// main.js Entry fileImport router from'./router'; / / introduced routingRouter.afterEach ((to, from) => {IfRecord & & to.name! = ='login') {Router.push ({name:'login'}); / / jump login}});

Well, through router.beforeEach, it can also be achieved and better.

you don’t know keep-alive[, I guess you don’t know].

Most components don’t need to be rendered many times when developing Vue projects, so Vue provides a built-in componentkeep-alive To cache the internal state of the component and avoid rendering it again, the document is here.

Document: and

cache dynamic components:

When wrapping dynamic components, it doesn’t make much sense to cache inactive component instances rather than destroy them.

    <!-- Basic -->< keep-alive>< component: is= "view" > < /component>< /keep-Alive><!! -- sub components --> with multiple conditions.< keep-alive>< comp-a v-if= "a > 1"> < /comp-a>< Comp-B v-else> < /comp-b>< /keep-alive>
<keep-alive> <router-view></router-view> </keep-alive>

active” is called at the first rendering of the component, and then at each activation of the cache component.

activated calling time:

After mounted, beforeRouteEnter guards the callback function passed to next before calling:

    beforeMount=> If you come in from other routing / components (components destroy destroyed/ or leave cache deactivated) =>Mounted=> activated enters cache component => executes befor.ERouteEnter callback

Because components are cached, they will not be triggered when they enter caching routing / components again.

    // beforeCreate created beforeMount mounted Will not trigger.

So the timing of the call is:

    Component destroys destroyed/ or leaves cache deactivated => activated enters current cache component.=> execute beforeRouteEnter callback./ / component cacheOr destroy, the destruction and cache of nested components are also triggered here.
deactivated: the component is disabled (leaving the route)”.
> cache the route you want to cache:
Vue2.1.0:”

To achieve similar operations, you can:

  1. Configuring routing element information

  2. Create two keep-alive Tags

  3. Use V-IF to determine which routes to cache by routing meta information.
 <keep-alive>
     <router-view v-if="$route.meta.keepAlive">
         <!--Here is the routing --> that will be cached.< /router-view>< /keep-alive>< router-view v-if= "! $route.meta.KeepAlive "><!! - because V-IF is used, so we have to create an un cached routing view export -->.< /router-view>//router configurationNEW Router ({Routes: [{Path: '/',Name:'home',Component: Home,Meta: {KeepAlive: true / / need to be cached}},{Path: '/: id',Name'edit',Component: Edit,Meta: {KeepAlive: false / / do not need to be cached.}}]});
> New Attribute:
  • include:The matching route / component will be cached.
  • exclude:The matching route / component will not be cached.

includeAnd exclude supports conditional cache routing in three ways: comma-separated string, regular, and array.

Regular and array forms must be used in the form of v-bind.

<!-- Comma separates string -->< keep-alive include= "a, B" >< component: is= "view" > < /component>< /keep-alive><! - regular expression (using `v-bind`) -->< keep-alive: include= "/a|b/" >< component: is= "view" > < /component>< /keep-alive>≪! - array (using `v-bind`) -->< keep-alive: include= "['a','b']" >< component: is="View" > < /component>< /keep-alive>

But in more scenarios, we will use keep-alive to cache Routing:

<keep-alive include='a'>
    <router-view></router-view>
</keep-alive>
<keep-alive include="a,b" exclude="a"> <!--Only a is not cached -->< router-view> < /router-view>< /keep-alive>

When components are matched by exclude, the component will not be cached and will not invoke activated and deactivated.

This picture is very clear, and many people are very clear about this part, most of the life cycle will not be used, here are a few points:

  1. ajaxThe request is best placed in the create, because this is now accessible, and the request to the data can be placed directly in the data.
    Here also met several times, the interviewer asks: which lifecycle should Ajax request be placed in.

  2. The operation of DOM should be placed in mounted, and DOM will be undefined before mounted.

  3. Every time you enter / leave components, you have to do something.

  • Not caching:
    You can enter with the create and mounted hooks, leave with the beforeDestory and destroyed hooks, beforeDestory can access this, destroyed can not access this.

  • Cache components:
    After caching the component, re-entering the component does not trigger beforeCreate, created, beforeMount, mounted, and if you want to do something every time you enter the component, you can put the activate in the cache componentIn the hook.

Similarly: BeforeDestroy and destroyed do not trigger when leaving the cache component, instead of using the hook that deactivated leaves the cache component.

conclusion

VueA lot of hooks are provided, but a lot of hooks are seldom used. Only when we know the triggering sequence of these hook functions and the restrictions behind them, can we use these hooks correctly. Hope that the students who have read this article can have a clearer understanding of these hooks and use them more easily..

Source: OBKoro1

Leave a Reply

Your email address will not be published. Required fields are marked *