Vue自定义指令、Mixin、Extends、Provide&Inject

一、自定义指令

1.1 全局指令

Vue.directive('指令名', directiveOptions)

1.2 局部指令

new Vue({
  ...,
  directives: {
    '指令名': directiveOptions
  }
})

1.3 directiveOptions的属性

  • bind(el, info, vnode, oldVnode) —— 类似于 created
  • inserted(el, info, vnode, oldVnode) —— 类似于 mounted
  • update(el, info, vnode, oldVnode) —— 类似于 updated
  • componentUpdated(el, info, vnode, oldVnode) —— 基本上用不到
  • unbind(el, info, vnode, oldVnode) —— 类似于 destroyed

1.4 使用方式

<div v-指令名="参数"></div>

1.5 代码示例,模拟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('测试')
    }
  }
})
<div v-on2:click="fn">我是假的v-on</div>

1.6 函数简写

如果 bindupdate 的内容一致时,并不关心其他钩子,可以使用此简写。

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

二、Mixin混入

需要混入的内容 mixins/test.js

data(){
  return {
    msg: '我是测试的内容'
  }
},
methods: {
  onSay(){
    console.log(this.msg)
  }
},
created() {
  console.log('我是测试的生面周期钩子')
}

需要混入的文件 Demo.vue

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

混入说白了就是复制粘贴

三、Extends继承、拓展

需要继承的文件 DemoVue.js

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

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

需要使用该继承的地方

import DemoVue from '../DemoVue.js'

new Vue({
  extends: DemoVue
})

或者

new DemoVue({
  构造选项
})

四、Provide & Inject

使用 provide 将属性暴露出去

Demo1.vue

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

其他组件就可以使用 inject 获取暴露出来的值

new Vue({
  inject: ['color', 'changeColor'],
  methods: {
    showColor(){
      console.log(this.color)
      this.changeColor()
      console.log(this.color)
    }
  }
})
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值