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

【Vue】自定义指令(directive)、管道命令(filters)_第1张图片

directive、filters

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

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

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

  return function (...args) {
    if (timer) clearTimeout(timer);

    const now = new Date().getTime()
    const laster = immediate && now - (timestamp ?? 0) > wait

    timer = laster ? func.apply(this, args) : setTimeout(function () {
      func.apply(this, args); timestamp = timer = null;
    }, wait)
    timestamp = now
  }
}

新建工具类文件 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)
  })
})

你可能感兴趣的:(Vue,JS,javascript,vue.js,es6)