【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)
  })
})
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章