【Vue】自定义指令(directive)、管道命令(filters)

在这里插入图片描述

directive、filters

指令以防暴力为例,调用示例 v-preventReClick:wait="a.bind(this)"
管道命令常用于日期格式化,调用示例 {{ val | timeFormat }}"

官方文档: Vue => 自定义指令

/**
 * 防反跳。func函数在最后一次调用时刻的wait毫秒之后执行!
 * @param func 执行函数
 * @param wait 时间间隔
 * @returns {Function}
 */
export function debounce(func, wait) {
  let timer = null

  return function (...args) {
    if (timer) clearTimeout(timer);
    timer = setTimeout(function () {
      func.apply(this, args)
      timer = null
    }, wait)
  }

新建工具类文件 globalVue.js,通过 Vue bind 事件进行注册,局部注册的话可以在 mounted 进行重载 this.func = debounce(this.func, 100)

import { 
  isFunction,
  debounce
} from './util'

import moment from 'moment';

// 全局公用方法
export const globalUtil = {}

export default {
  // 全局指令
  directive: {
    preventReClick: {
      bind(el, { value, arg = 250 }) {
        if (isFunction(value)) {
          el.addEventListener("click", debounce(value, arg))
        }
      }
    }
  },
  // 全局过滤器
  filter: {
    timeFormat(val) {
      return moment().format(val)
    }
  }
}

脚手架工程的话,直接在 main.js 中引入

import Vue from 'vue'

import { 
  default as globalVue, 
  globalUtil
} from './globalVue'

// 自定义全局公用类、指令、过滤器
Vue.prototype.$util = globalUtil

Object.entries(globalVue).forEach(([name, item]) => {
  Object.entries(item).forEach(([key, value]) => {
    Vue[name](key, value)
  })
})
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章