Detailed explanation of Vue instance initialization options and configuration objects, front-end development mainstream framework

Example:

var vm = new Vue({

  data: { a: 1 },

  methods: {

    plus: function () {

      this.a++

    }

  }

})

vm.plus()

vm.a // 2 

1.4. watch

type

{ [key: string]: string | Function | Object }

Details:

For an object, the key is the expression to be observed, and the value is the corresponding callback function. The value can also be a method name or an object containing options. The Vue instance will call $watch() when instantiating, traversing each property of the watch object.

Example:

var vm = new Vue({

  data: {

  

  }, 

watch: {

//This function is automatically executed when monitoring the change of a variable

a: function (val, oldVal) {

console.log('new: %s, old: %s', val, oldVal)

},

//Depth watcher

c: {

handler: function (val, oldVal) { /* ... */ },

deep: true

}

}

})

vm.a = 2 // -> new: 2, old: 1

//Note that the arrow function should not be used to define the watcher function (for example, searchquery: newvalue = > this. Updateautocomplete (newvalue)). The reason is that the arrow function binds the context of the parent scope, so this will not point to the Vue instance as expected, and this.updateAutocomplete will be undefined.

Refer to the comprehensive case:

<!DOCTYPE html> 

<html lang="en">

<head>

  <meta charset="UTF-8">

  <title>Vue Introduction to data monitoring</title>

  <script src="https://unpkg.com/vue/dist/vue.js"></script>

</head>

<body>

  <div id="app">

    <p>{{ number }}</p>

    <input type="button" name="btnGetNumber" value="increase" v-on:click="getNumber()">

  </div>

  <script>

    var app = new Vue({         

      el: '#app',               

      data: {                   

        number: 1

      },

      methods: {

        // Logical code of event response method

        getNumber: function (e) {

          this.number += 1;   // this points to the app when executing the event response method either by inline method call or by binding the event handler

        }

      },

      watch: {

        // Monitor the change of number and automatically execute the following function

        number: function (val, oldVal) {

          console.log('val:' + val + ' - oldVal: ' + oldVal);

        }

      }

    });

  </script>

</body>

</html> 

1.5. Detailed explanation of setting el

type

string | HTMLElement

Restriction: only in instances created by new.

Details:

Provide an existing DOM element on the page as the mounting target of Vue instance, that is, where to find Vue binding data. It can be a CSS selector or an HTMLElement instance.

After the instance is mounted (the content of the life cycle will be described in detail later), the elements can be accessed with vm.$el.

If this option works during instantiation, the instance will immediately enter the compilation process. Otherwise, you need to explicitly call vm.$mount() to manually start compilation.

//Almost all examples use this, so I won't repeat it

var app = new Vue({

el: '#app',

...

});

1

2

3

4

5

2. Life cycle of Vue instance

Vue instances have a complete life cycle, that is, a series of processes such as creating, initializing data, compiling templates, mounting Dom, rendering → updating → rendering and unloading. We call this the life cycle of Vue. Generally speaking, it is the process from creation to destruction of Vue instances, which is the life cycle.

In the whole life cycle of Vue, it provides a series of events that allow us to register js methods and enable us to reach the destination of controlling the whole process. Wow, Sai, [if you have been involved in Asp.Net](

)If WebForm, you will find that the whole is a replica of WebForm. Ha ha. It is worth noting that this in these event response methods directly points to the instance of vue.

First, let's take a look at a life cycle diagram on the official website below. I'll mark it and see the overall process. Later, we'll do the effect on the code.

Insert a picture description here. The hooks that Vue provides that can be registered are marked in the red box of the picture. They are:

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 has completed the following configuration: Data observer, operation of properties and methods, and callback of watch/event events. However, the mount phase has not yet started and the $el attribute is not currently visible.

beforeMount

Called before the mount starts: the related render function is called for the first time.

mounted

El is replaced by the newly created vm.el and is mounted on the instance to invoke the hook. If the root instance mounts an element in the document, when the mounted is called, vm.el is replaced and mounted to the instance to invoke the hook. If the root instance mounts an element in the document, vm.el is also in the document when mounted is called.

beforeUpdate

Called when the data is updated, which occurs before the virtual DOM is re rendered and patched. You can further change the state in this hook, which does not trigger an additional re rendering process.

updated

The hook is invoked 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. However, in most cases, you should avoid changing the state during this period, as this may lead to an infinite loop of updates.

The hook is not called during server-side rendering.

beforeDestroy

Before the instance is destroyed, it is called. At this step, the instance is still fully available.

destroyed

After the Vue instance is destroyed, it is called. After calling, everything indicated by the Vue instance will be unbound, all event listeners will be removed, and all sub instances will be destroyed. The hook is not called during server-side rendering.

Next, let's take an example to see how all the life cycles in Vue are used.

<!DOCTYPE html> 

<html lang="en">

<head>

  <meta charset="UTF-8">

  <title>Vue Life cycle of introduction</title>

  <script src="https://unpkg.com/vue/dist/vue.js"></script>

</head>

<body>

  <div id="app">

    <p>{{ number }}</p>

    <input type="text" name="btnSetNumber" v-model="number">

  </div>

  <script>

    var app = new Vue({         

      el: '#app',               

      data: {                   

        number: 1

      },

      beforeCreate: function () {

        console.log('beforeCreate Hook execution...');

        console.log(this.number)

      },

      cteated: function () {

        console.log('cteated Hook execution...');

        console.log(this.number)

      },

      beforeMount: function () {

        console.log('beforeMount Hook execution...');

        console.log(this.number)

      },

      mounted: function () {

        console.log('mounted Hook execution...');

        console.log(this.number)

      },

      beforeUpdate: function () {

        console.log('beforeUpdate Hook execution...');

        console.log(this.number)

      },

      updated: function () {

        console.log('updated Hook execution...');

        console.log(this.number)

      },

      beforeDestroy: function () {

        console.log('beforeDestroy Hook execution...');

        console.log(this.number)

      },

      destroyed: function () {

        console.log('destroyed Hook execution...');

        console.log(this.number)

      },

    });

  </script>

</body>

</html> 

Let's take another comprehensive practical example, which may involve ajax and components, but let's take a look at the usage of the example of vue's life cycle:

import Axios from 'axios'       // This is a lightweight ajax library, and import is the syntax of es6 module import.

export default {                // This is a vue module, which will be discussed later.

  name: 'app',

  components: {

  },

  data: function () {

    return {

      list: []

    }

  },

  mounted: function () {          // Hang the hook registration after the completion of the life cycle.

    this.$nextTick(function () {  // Execute the business processing code after the next update is completed.

      Axios.get('/api/menulist', {// Delay the callback until after the next DOM update cycle. Use it immediately after modifying the data, and then wait for the DOM to update

        params: {

        }

      }).then(function (res) {

        this.list = res.data

      }.bind(this))

    })

  }

} 

  1. Global configuration of Vue instances

Tags: Javascript Front-end Vue.js css Programmer

Posted on Fri, 10 Sep 2021 01:06:26 -0400 by Ringo