1. Pictures of the life cycle on vUE official website

2. Detailed list

At various stages in the lifecycle of a VUE instance, different hook functions are provided to perform different operations. First list the vue official website for each hook function detailed analysis.

Lifecycle hook detailed
beforeCreate After instance initialization, data Observer and Event/Watcher events are called before configuration.
created Called after the instance has been created. In this step, the instance completes the configuration of data Observer, property and method operations, and Watch/Event event callbacks. However, the mount phase has not yet started and the $EL attribute is not currently visible.
beforeMount Called before the mount begins: The associated render function is called for the first time.
mounted El Specifies the newly created VM.
e l Replace and mount the hook to the instance. if r o o t The instance mounts a document element when m o u n t e d Is called v m . El replaces and is called after being mounted to the instance. If the root instance mounts an element within a document, the VM is called when Mounted.
El is also in the document.
beforeUpdate Called when data is updated, before the virtual DOM is re-rendered and patched. You can further change the state in this hook without triggering additional rerendering.
updated This hook is called after the virtual DOM is re-rendered and patched due to data changes. When this hook is called, the component DOM has been updated, so you can now perform DOM-dependent operations.
activated Called when the keep-alive component is activated.
deactivated Called when the keep-alive component is disabled.
beforeDestroy Called before instance destruction. At this step, the instance is still fully available.
destroyed Called after the Vue instance is destroyed. When called, everything indicated by the Vue instance is unbound, all event listeners are removed, and all subinstances are destroyed.

3. Example code hook execution:

// Child component Child1
<template>
    <div>Give me a div</div>
</template>

<script>
export default {
    beforeCreate() {
        console.log('beforeCreate executed ')},created() {
        console.log('Created executes')},beforeMount() {
        console.log('beforeMount executed ')},mounted() {
        console.log('mounted executed ')},beforeUpdate() {
        console.log('beforeUpdate executed ')},updated() {
        console.log('updated ')},beforeDestroy() {
        console.log('beforeDestroy executed ')},destroyed() {
        console.log('destroyed executed ')}},</script>

// Parent App
<template>
    <div>
        <button @click="flag = ! flag">Click Destroy to create the child component</button>
        <Child1 v-if="flag" />
    </div>
</template>

<script>
import Child1 from './components//Child1'
export default {
    data() {
        return {
            flag: true,}},components: {
        Child1,
    },
}
</script>
Copy the code

1. Launch the hook for the first time the project loads the page:

2. Click the button to destroy the hook executed by Child1:

Vue – Route Guard (Lifecycle of routes)

1. Route navigation guard definition

Official explanation:

Navigation indicates that the route is changing. True to its name, vue-Router provides navigational guards that are primarily used to guard navigation by jumping or cancelling. There are several opportunities for embedding route navigation: global, single route proprietary, or component level.

To put it simply, a navigational guard is a set of hook functions during a route jump. The route jump is a big process, the big process is divided into before, after and so on small process, in each process has a function, this function allows you to operate on something else, this is the navigation guard. Similar to component lifecycle hook functions

2. Route guard classification

[1] Global guard: refers to a hook function operated directly on a routing instance. It features that all routing configuration components will trigger

  • BeforeEach (to, from, next)
  • BeforeResolve (to, from, next)
  • AfterEach (to, from)

[2] Route guard: a hook function that can also be set during the configuration of a single route

  • BeforeEnter (to, from, next)

[3] Component guard: refers to the hook function executed in the component, which is similar to the life cycle of the component, and is equivalent to the life cycle hook function added for the component configured with routing.

  • BeforeRouteEnter (to, from, next)
  • BeforeRouteUpdate (to, from, next)
  • BeforeRouteLeave (to, from, next)

3. Route guard callback parameters

To: indicates the destination route object to be entered.

From: the route object to leave.

Next: The hook function that refers to the next argument must call the next() method to resolve the hook, otherwise the route will break and will not proceed

  • Next () : Goes to the next hook in the pipe. If all hooks are executed, the navigation state is confirmed.
  • Next (false) interrupts the 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({paht: ‘/’}) : jumps to a different address. The current navigation is interrupted and a new navigation is performed. Passable arguments can be the to attribute parameter in the router-link tag or an option in router.push
  • Next (error) : If the argument passed to Next is an instance of error, the navigation is terminated and the error is passed to the callback registered with router.onerror ().

4. Route guard details

[1] Global front-guard (beforeEach) : Triggered before route redirects. This hook is mainly used for login authentication, that is, notifying a route before it redirects so that it is too late to notify it again.

const router = new VueRouter({ ... })
​
router.beforeEach((to, from, next) => {
  // ...
})
Copy the code

[2] beforeResolve: This hook is similar to beforeEach in that it fires before a route jump, except that it is called before navigation is acknowledged and after guard and asynchronous routing components are resolved within all components, after beforeRouteEnter within each and before afterEach.

[3] afterEach: In contrast to beforeEach, it fires after the jump is complete. It happens after beforeEach and beforeResolve, and before beforeRouteEnter. These hooks do not accept the next function nor change the navigation itself

router.afterEach((to, from) => {
  // ...
})
Copy the code

[4] Exclusive guard (beforeEnter) : exactly the same as beforeEach, if both are set, beforeEnter is executed immediately after beforeEach. Define the beforeEnter guard directly on the route configuration

const router = new VueRouter({
  routes: [
    {
      path: '/foo',
      component: Foo,
      beforeEnter: (to, from, next) => {
        // ...
      }
    }
  ]
})
Copy the code

[5] Guards in components:

<template> ... </template> <script> export default{ data(){ //... }, beforeRouteEnter (to, from, next) {// Call the render component before the corresponding route is confirmed // no! Can!!!! }, beforeRouteUpdate (to, from, next) {// Called when the current route changes but the component is being reused. For example, For a path /foo/:id with dynamic parameters, the component instance will be reused as // renders the same foo component when jumping between /foo/1 and /foo/2. And the hook will be called in that case. }, beforeRouteLeave (to, from,); Next) {// navigate away from the corresponding route of the component // can access the component instance 'this'}} </script> <style>... </style>Copy the code

1. BeforeRouteEnter: This hook is called after the global guard beforeEach and exclusive guard beforeEnter, and before global beforeResolve and afterEach. Note that there is no instance of the component in this guard, i.e. this is undefined. Because it fires during the component lifecycle beforeCreate phase, the new component has not yet been created. In this hook function, you can access the component instance by passing a callback to Next. The callback is executed when the navigation is validated, and the component instance is taken as an argument to the callback method.

BeforeRouteEnter (to, from, next) {next(vm => {// access component instance through 'VM'})}Copy the code

BeforeRouteUpdate: called when the current route changes and the component is being reused, the instance can be accessed through this.

3. BeforeRouteLeave: called when navigating away from the corresponding route of the component, which can be accessed by component instance this. This departure guard is usually used to prevent the user from leaving suddenly without saving the changes. This navigation can be cancelled by next(false).

beforeRouteLeave (to, from , next) { const answer = window.confirm('Do you really want to leave? you have unsaved changes! ') if (answer) { next() } else { next(false) } }Copy the code

5. Complete navigation parsing process

  1. Trigger to enter other routes
  2. Call the component guard beforeRouteLeave to leave the route
  3. Call the global front-guard beforeEach
  4. Call beforeRouteUpdate in the reused component
  5. Call beforeEnter in routing configuration
  6. Parse the asynchronous routing component
  7. Call beforeRouteEnter in the incoming routing component
  8. Call the global parse guard beforeResolve
  9. Navigation confirmed
  10. Call the global afterhook afterEach.
  11. DOM update Mounted is triggered.
  12. Execute the callback passed to Next in the beforeRouteEnter guard.