Vue.directive( id, [definition] )

  • Parameters:

    • {string} id
    • {Function | Object} [definition]

Usage:

Register or get global directives.

Directives object properties are defined in cache. js

  • bind: called only once, the first time a directive is bound to an element. This is where you can perform one-time initialization Settings.
  • inserted: called when the bound element is inserted into the parent node (the parent node is guaranteed to exist, but not necessarily inserted into the document). Several instructions are called several times at a time
  • update: called when the VNode of the component is updated,But it can happen before its child VNode is updated. The value of the instruction may or may not have changed. However, you can ignore unnecessary template updates by comparing the values before and after the update (see below for detailed hook function parameters).
export const imageError = {
  // INSERTED is the hook function: this defines when the element bound by the directive is inserted into the parent node
  inserted(dom, binding) {
    // dom is the element img bound to the directive
    // binding is an object whose value is a variable bound by the directive
    console.log(dom)
    console.log(binding)
    // Determine if the image is empty
    // dom.src = dom.src || binding.value
    if(! dom.src) { dom.src = binding.valuereturn
    }
    // Failed to load images
    //.onerror is the function that img failed to load
    dom.onerror = function() {
      dom.src = binding.value
    }
  }
}
Copy the code

Expose all directives in directives/index.js

import Vue from 'vue'
import * as directives from '@/directives/directives'
// Register custom directives
Object.keys(directives).forEach(key= > {
  Vue.directive(key, directives[key])
})
Copy the code

Import all directives in main.js from SRC in the vue project

import '@/directives'
Copy the code