Custom instruction

Instructions are used to simplify DOM operations and encapsulate the underlying DOM operations. We can customize directive Settings when we want to use some DOM functionality that the built-in directives don’t have.

The official documentation

Custom global directives

Refers to instructions that can be used by any Vue instance or component.

Directive (arg1, arg2) creates function * arg1 custom directive name * arg2 configuration object */ 
/** * INSERTED (el, binding) Hook function, which defines the operation to be performed while the element is inserted into the DOM * EL is optional, the element that is set to the current directive * binding is optional, and information about the current directive is set */
Vue.directive('focus', {
  inserted (el, binding) {
    console.log(el)
    console.log(binding)
    // The element gets focus
    el.focus()
  }
})
Copy the code

Using custom directives:

<! -- To use custom instruction, add v before the name.
<input type="text" v-focus>
Copy the code

Custom local directives

Refers to an instruction that can only be used by the current Vue instance or component.

const vm = new Vue({
  el: '#app'.data: {},
  directives: {
    focus: {
      inserted (el) {
        el.focus()
      }
    }
  }
})
Copy the code

Using custom local directives:

<div id="app">
  <input type="text" v-focus>
</div>
Copy the code

The filter

Filters are used for text content formatting processing. Filters can be used in the interpolation expressions and v – bind instruction, transfer data through the pipeline operator |.

Global filter

Can be used in any Vue instance.

// Set the global filter
Vue.filter('filterA'.function (value) {
  return value.split(The '-').join(' ')})// A filter can pass in multiple arguments
Vue.filter('filterC'.function (par1, par2, par3) {
  return par2 + par1.split(The '-').join(' ');
})
Copy the code

Use global filters:

<p v-bind:title="value | filterA">This is the label</p>
<p>{{ value2 | filterA }}</p>

<! -- Can pass a data into multiple filters, first left and then right -->
<p>{{ value | filterA | filterB }}</p>

<! Select * from 'QQQ -',' QQQ -', '2', '3' -->
<p>{{ value | filterC('qqq-', 200) }}</p>
Copy the code

Local filter

Can only be used in the current Vue instance.

new Vue({
  el: '#app'.data: {},
  filters: {
    filterA: function (value) {
      return value.split(The '-').join(' ')},filterB: function (value) {
      return value.split(' ').reverse().join(' ')
    },
    filterC (value, prefix) {
      returnprefix + value; }}})Copy the code

Calculate attribute

The vue.js view does not recommend writing complex logic, which is not conducive to maintenance. Wrapping functions is a good way to do this, but sometimes repetitive calculations consume unnecessary performance. And vue. Js calculation attribute executable function, and can avoid repeated calculation.

The official documentation

Basic usage

const vm = new Vue({
  el: '#app'.data: {
    arr: [1.2.3.4.5]},// Calculate attributes
  computed: {
    getResult () {
      console.log('Evaluated property performed');
      var arr = this.arr;
      var sum = 0;
      for (var i = 0; i < arr.length; i++) {
            sum += arr[i];
      }
      returnsum; }}})Copy the code

Call calculated property

<! -- Calculated attributes cannot add () -->
<p>{{ getResult }}</p>

<ul>
  <! -- Evaluate attributes with the V-for directive -->
  <li v-for="item in result">{{ item }}</li>
</ul>
Copy the code

Differences between Methods and computed Data:

  • Computed is cached, whereas Methods is not
  • Computed is accessed by attribute name, and methods needs to be called
  • Computed only works for computed operations, not if there are DOM operations inside a function

setter

Compute properties only have getters by default, but setters can also be set, which are generally used to update the overall data.

computed: {
  // Default writing mode:
  /* fullName () { return this.firstName + this.lastName; } * /
  // Write getter and setter separately
  fullName: {
    get () {
      return this.firstName + this.lastName;
    },
    set (newValue) {
      console.log(newValue)
      var nameArr = newValue.split(' ');
      this.firstName = nameArr[0];
      this.lastName = nameArr[1]; }}}Copy the code

Setting computing Properties

vm.fullName = 'three zhang'
Copy the code

The listener

Listeners are used to listen for data changes and perform specified actions.

The official documentation

Basic usage

var vm = new Vue({
  el: '#app'.data: {
    value: ' '
  },
  // listen for data value changes
  watch: {
    value () {
      console.log('Listener executed')}}})Copy the code

Using listeners

<input type="text" v-model="value">
Copy the code

Listening to the object

You need to set the deep: true attribute and use the handler() function to perform the specified operation.

watch: {
  obj: {
    deep: true,
    handler (val, oldVal) {
      // The object reference we are listening for does not change when the inner element of an object or array changes.
      // The new value and the old value are the same reference, so we really only need one argument line val
      console.log('OBj has been modified', val, oldVal)
      console.log(val === oldVal)
    }
  }
}
Copy the code

Listening to the array

watch: {
  arr (val, oldVal) {
    console.log('ArR has been modified', val, oldVal)
    console.log(val === oldVal)
  }
}
Copy the code

Note: Instead of using indexes and length for array operations, use push() and vue.set (), otherwise listener functions will not fire.

Vue DevTools

Vue DevTools is a tool provided by Vue. Js for debugging Vue applications.

It can be added by searching for Vuejs Dev in the App store in Google Chrome.

Matters needing attention:

  • To see Vue DevTools, you must have the Vue
  • Web pages must use vue.js instead of vue.min.js
  • Web pages need to be opened under THE HTTP protocol, not locally using the File protocol

The basic use

  1. Use the plug-in Live Server in VS Code to open the web page you want to debug

2. Right-click and choose Check, find Vue in the arrow on the right, and click

3. View the modified data in the debugging tool

The lifecycle of vue.js

This refers to the process of creating, running, and destroying Vue instances.

Vue.js life cycle diagram:

Lifecycle hook

Lifecycle hooks enable functionality to be performed at a specific phase of the lifecycle.

  1. Create a stage

    • BeforeCreate: called before instance initialization
    • Created: called after instance creation (data, methods, etc.)
    • BeforeMount: called before the instance is mounted
    • Mounted: The instance is mounted to a DOM element.

    Features: Each instance can only be executed once.

  2. Operation phase

    • BeforeUpdate: Called after data is updated before view is updated
    • Updated: Invoked after the view is updated

    Features: Call on demand.

  3. Destruction of phase

    • BeforeDestroy: Called before instance destruction
    • Destroyed: Called after the instance is destroyed

    Features: Each instance can only be executed once.