vue-cli自定义指令-批量导入

668 阅读2分钟

「这是我参与11月更文挑战的第3天,活动详情查看:2021最后一次更文挑战

项目中,为了方便开发,我们可能需要自定义多个指令,少了还好,多的话就会造成一个文件内代码太多,不好看,还麻烦,这时就需要批量注册自定义指令。

方式一

将每个指令单独放在js文件中目录结构如下

image.png

以图为例,将为drag,longpress,relativeTime指令各自建立js文件存放在directives目录下,再从index.js中统一导出

directives/longpress.js

drag.js、relativeTime.js也同理,关键代码见 上文

const longpress = {
    bind: function (el, binding, vNode) {
      if (typeof binding.value !== 'function') {
        throw 'callback must be a function'
      }
      // 定义变量
      let pressTimer = null
      // 创建计时器( 2秒后执行函数 )
      let start = (e) => {
        if (e.type === 'click' && e.button !== 0) {
          return
        }
        if (pressTimer === null) {
          pressTimer = setTimeout(() => {
            handler()
          }, 2000)
        }
      }
      // 取消计时器
      let cancel = (e) => {
        if (pressTimer !== null) {
          clearTimeout(pressTimer)
          pressTimer = null
        }
      }
      // 运行函数
      const handler = (e) => {
        binding.value(e)
      }
      // 添加事件监听器
      el.addEventListener('mousedown', start)
      el.addEventListener('touchstart', start)
      // 取消计时器
      el.addEventListener('click', cancel)
      el.addEventListener('mouseout', cancel)
      el.addEventListener('touchend', cancel)
      el.addEventListener('touchcancel', cancel)
    },
    // 当传进来的值更新的时候触发
    componentUpdated(el, { value }) {
      el.$value = value
    },
    // 指令与元素解绑的时候,移除事件绑定
    unbind(el) {
      el.removeEventListener('click', el.handler)
    },
  }
  
  export default longpress

directives/index.js

将所有指令的js文件通过import导入至index.js后再将其包装为对象,通过Object.keys().forEach将对象循环注册

import drag from './drag'
import relativeTime from './relativeTime'
import longpress from './longpress'
// 将自定义指令包装为对象
const directives = {
  drag,
  longpress,
  relativeTime
}
//将对象循环注册在导出
export default {
  install(Vue) {
    Object.keys(directives).forEach((key) => {
      Vue.directive(key, directives[key])
    })
  },
}

main.js

通过Vue.use()全局注册

import Directives from './assets/js/directives/index'
Vue.use(Directives)

我们后续如果需要增加新指令时,只需为新增指令单独创建js文件放在directives/index.js的同级目录下,然后再index.js中进行引入就可以全局使用了

方式二

推荐一个比较好用的依赖包,包含了多种自定义指令

包含了

  • 复制粘贴指令 v-copy
  • 长按指令 v-longpress
  • 输入框防抖指令 v-debounce
  • 禁止表情及特殊字符 v-emoji
  • 权限校验指令 v-premission
  • 实现页面水印 v-waterMarker
  • 拖拽指令 v-draggable

下载依赖包

npm install cm-directives --save

注册

import cmDirectives from 'cm-directives'
Vue.use(cmDirectives)

使用

<template>
  <div v-draggable>我可以拖动哦!!!</div>
</template>