1. Custom instructions

1.1 Global Instructions

Vue.directive('Directive name', directiveOptions)
Copy the code

1.2 Local instructions

newVue({ ... .directives: {
    'Directive name': directiveOptions
  }
})
Copy the code

1.3 directiveOptions properties

  • Bind (EL, info, vnode, oldVnode) – similar to created
  • Inserted (el, info, vnode, oldVnode) — similar to Mounted
  • Update (EL, info, vNode, oldVnode) — similar to updated
  • ComponentUpdated (EL, INFO, VNode, oldVnode) — basically not needed
  • Unbind (EL, info, vnode, oldVnode) – similar to destroyed

1.4 Usage Mode

<div v-Command name ="Parameters"></div>
Copy the code

1.5 code examples, simulate V-ON

new Vue({
  directives: 
    'on2': {
      inserted(el, info){
        el.addEventListener(info.arg, info.value)
      },
      unbind(el, info){
        el.removeEventListener(info.arg, info.value)
      }
    }
  },
  methods: {
    fn(){
      console.log('test')}}})Copy the code
<div v-on2:click="fn">I'm a fake V-ON</div>
Copy the code

1.6 Function shorthand

You can use this shorthand if you don’t care about other hooks when bind and update are identical.

Vue.directive('color-swatch'.(el, binding) = >{
  el.style.backgroundColor = binging.value
})
Copy the code

Second, Mixin

Content mixins/test.js to be mixed in

data(){
  return {
    msg: 'I am the subject of the test.'}},methods: {
  onSay(){
    console.log(this.msg)
  }
},
created() {
  console.log('I'm testing the raw dough cycle hook.')}Copy the code

Need to mix in the file demo.vue

import test from '.. /mixins/test.js'
new Vue({
  mixins: [test]
})
Copy the code

Mixin is basically copy and paste

Extends Extends

The file demovue.js needs to be inherited

import Vue from 'vue'
import test from '.. /mixins/test.js'

const DemoVue = Vue.extend({
  mixins: [test]
})
Copy the code

Where you need to use this inheritance

import DemoVue from '.. /DemoVue.js'

new Vue({
  extends: DemoVue
})
Copy the code

or

newDemoVue({construct option})Copy the code

Provide and Inject

Expose properties using provide

Demo1.vue

new Vue({
  data(){
    return {
      color: 'red'}},methods: {
    changeColor(){
      this.color = 'blue'}},project(){
    return {
      color: this.color,
      changeColor: this.changeColor
    }
  }
})
Copy the code

Other components can use Inject to get exposed values

new Vue({
  inject: ['color'.'changeColor'].methods: {
    showColor(){
      console.log(this.color)
      this.changeColor()
      console.log(this.color)
    }
  }
})
Copy the code