Vue life cycle and components

Vue lifecycle hooks

  • Origin of hook function

    Each Vue instance goes through a series of initialization processes when it is created - for example, it needs to set up data listeners, compile templates, mount the instance to the DOM and update the DOM when the data changes, etc. At the same time, some functions called lifecycle hooks are also run during this process, which gives users the opportunity to add their own code at different stages.

    In a popular understanding, the Vue object manages a label and renders the data to the specified location, just like you are the urban management of the street and manage the street, and the same is true for the later components, the object manages a certain html fragment;

  • Lifecycle hook function

    Before and after creation, before and after rendering, before and after update, before and after destruction, a total of eight

    hook function describe
    beforeCreate Called before creating a Vue instance
    created Called after the Vue instance is successfully created (you can send asynchronous request backend data here)
    beforeMount Called before rendering the DOM, before the virtual DOM is mounted
    mounted Called after rendering the DOM, after the virtual DOM is mounted, see the page
    beforeUpdate Called before re-rendering (controls the DOM to re-render during data update and other operations)
    updated Called after re-rendering is complete
    beforeDestroy Called before destroy
    destroyed Called after destroy

    For example the created hook can be used to execute code after an instance is created:

    new Vue({
      data: {
        a: 1
      },
      created: function () {
        // `this` points to the vm instance
        console.log('a is: ' + this.a)
      }
    })
    // => "a is: 1"
    

    There are also some other hooks that are called at different stages of the instance lifecycle, such as mounted, updated and destroyed. The this context of a lifecycle hook points to the Vue instance that invoked it.

    not in options property or use arrow functions on callbacks, like created: () => console.log(this.a) or vm.$watch('a', newValue => this.myMethod()). Because arrow functions don't this,this will be used as a variable to look up the upper lexical scope until it is found, often resulting in Uncaught TypeError: Cannot read property of undefined or Uncaught TypeError: this.myMethod is not a function errors like that.
    

    Notice

    • created to create an instance, can send a request to get data from the backend
    • mounted can set timed tasks, delay tasks...
    • beforeDestroy set to cancel timed tasks...
  • life cycle diagram

  • Hook function test

    Vue The subject cannot see the effect process, define a component to test.
    Hook functions are at the same level as parameters.
    console.group()group display
    console.groupEnd() end group
    
    this.Properties View the current object data define attribute value in attribute.
    this.$Attributes, View the properties of the current object,
    
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Vue The life cycle</title>
        <script src="js/vue.js"></script>
    </head>
    <body>
    
    <div id="app">
        <button @click="headerClick">components(Add to/delete)</button>
        <model1 v-if="is_show">Display components</model1>
    </div>
    </body>
    <script>
        // Define Vue object -- role --> call component
        var vm = new Vue({
            el: '#app',
            data: {
                // component switch
                is_show: false,
            },
            // Component-bound click event
            methods: {
                headerClick() {
                    // one click on, one click off
                    this.is_show = !this.is_show
                }
            }
        })
    
        // define components
        Vue.component('model1',
            {
                template: `
                  <div>
                  <p>my name: {{ name }}</p>
                  <p>
                    <button @click="vary">Click to change name</button>
                  </p>
                  </div>
                `,
    
                // Variables that define components
                data() {
                    return {
                        name: 'kid'
    
                    }
                },
    
                // How to define components
                methods: {
                    vary() {
                        this.name = 'qq'
                    },
    
    
                },
                 beforeCreate() {
                        console.group('Current status: beforeCreate')
                        console.log('current el state:', this.$el)
                        console.log('current data state:', this.$data)
                        console.log('current name state:', this.name)
                        console.groupEnd()
                    },
                    created() {
                        console.group('Current status: created')
                        console.log('current el state:', this.$el)
                        console.log('current data state:', this.$data)
                        console.log('current name state:', this.name)
                        console.groupEnd()
                    },
                    beforeMount() {
                        console.group('Current status: beforeMount')
                        console.log('current el state:', this.$el)
                        console.log('current data state:', this.$data)
                        console.log('current name state:', this.name)
                        console.groupEnd()
                    },
                    mounted() {
                        console.group('Current status: mounted')
                        console.log('current el state:', this.$el)
                        console.log('current data state:', this.$data)
                        console.log('current name state:', this.name)
                        console.groupEnd()
    
                    },
                    beforeUpdate() {
                        console.group('Current status: beforeUpdate')
                        console.log('current el state:', this.$el)
                        console.log('current data state:', this.$data)
                        console.log('current name state:', this.name)
                        console.groupEnd()
                    },
                    updated() {
                        console.group('Current status: updated')
                        console.log('current el state:', this.$el)
                        console.log('current data state:', this.$data)
                        console.log('current name state:', this.name)
                        console.groupEnd()
                    },
                    beforeDestroy() {
                        console.group('Current status: beforeDestroy')
                        console.log('current el state:', this.$el)
                        console.log('current data state:', this.$data)
                        console.log('current name state:', this.name)
                        console.groupEnd()
                    },
                    destroyed() {
                        console.group('Current status: destroyed')
                        console.log('current el state:', this.$el)
                        console.log('current data state:', this.$data)
                        console.log('current name state:', this.name)
                        console.groupEnd() 
                    },
            }
        )
    </script>
    </html>
    
    • Add component display:

    • Component data update:

    • No task is created, no task is destroyed, and no actual effect can be seen.

    • create task destroy task

      1. mounted Create task in hook function
      2. beforeDestroy Hook function to re-destroy the created task
      
      setInterval: Timed execution,Print information every second.
      
      component destruction, cleanup timer
      clearInterval(this.f)
      this.f = null
      
      <!DOCTYPE html>
      <html lang="en">
      <head>
          <meta charset="UTF-8">
          <title>Vue The life cycle</title>
          <script src="js/vue.js"></script>
      </head>
      <body>
      
      <div id="app">
          <button @click="headerClick">components(Add to/delete)</button>
          <model1 v-if="is_show">Display components</model1>
      </div>
      </body>
      <script>
          // Define Vue object -- role --> call component
          var vm = new Vue({
              el: '#app',
              data: {
                  // component switch
                  is_show: false,
              },
              // Component-bound click event
              methods: {
                  headerClick() {
                      // one click on, one click off
                      this.is_show = !this.is_show
                  }
              }
          })
      
          // define components
          Vue.component('model1',
              {
                  template: `
                    <div>{{text}}</div>
                  `,
      
                  // Variables that define components
                  data() {
                      return {
                          // Define a variable receiving function
                          func: null,
                          text: 'printing information'
                      }
                  },
      
                  // define a scheduled task
                  mounted() {
                      //  anonymous arrow function
                      this.func = setInterval(()=>{
                          console.log('hello word!')
                      }, 1000)
      
                  },
      
                  // Destroy a scheduled task
                  beforeDestroy() {
                      // Clear scheduled tasks
                      clearInterval(this.func)
                      // clear value
                      this.func = null
                  },
              }
          )
      </script>
      </html>
      

Vue interacts with the backend

Tags: Vue

Posted by syacoub on Sat, 12 Nov 2022 23:51:56 +1030