- 首先我们可以再src目录下,创建一个directives的文件夹;
- 然后在directives文件夹里新建一个globalDirectives.js的文件;
-
// globalDirectives.js const globalDirectives = { /* * 文字超出省略 * width:宽度,非必传,默认100% * line:超出多少行显示省略号,非必传,默认1行 * 示例:v-ellipisis="{width:100,line:2}" */ ellipsis: (el, binding) => { let { width, line } = binding.value el.style.width = width ? width + 'px' : '100%' el.style.display = '-webkit-box' el.style.overflow = 'hidden' el.style.textOverflow = 'ellipsis' el.style['-webkit-line-clamp'] = line || 1 el.style['-webkit-box-orient'] = 'vertical' }, /* * 元素吸顶 * stickyNum:距离顶部多少px吸顶,非必传,默认0 * 示例:v-sticky="50" */ sticky: { bind: (el, { value }) => { const stickyNum = value || 0 window.addEventListener( 'scroll', globalDirectives.sticky.handleScroll(el, stickyNum) ) }, unbind: () => { window.removeEventListener( 'scroll', globalDirectives.sticky.handleScroll() ) }, handleScroll: (el, stickyNum) => { return () => { const scrollTop = window.scrollY || document.documentElement.scrollTop || document.body.scrollTop if (scrollTop >= el.offSetTop - stickyNum) { el.style.position = 'sticky' el.style.top = stickyNum + 'px' el.style.zIndex = 10 } else { el.style.position = 'stick' } } } }, /* * 点击事件防抖 * 参数:事件名称 * 示例:v-debounce = "eventName" */ debounce: { inserted: (el, { value }) => { el.addEventListener( 'click', globalDirectives.debounce.debounceEvent(value) ) }, unbind: (el, { value }) => { el.removeEventListener( 'click', globalDirectives.debounce.debounceEvent(value) ) }, debounceEvent: (value) => { let timeout return () => { if (timeout) clearTimeout timeout = setTimeout(() => { value() }, 500) } } } } export default globalDirectives
- 在directives文件夹里新建一个index.js的文件,完成批量定义
-
// index.js import globalDirectives from './globalDirectives' const directives = { install: function (app) { Object.keys(globalDirectives).forEach((key) => { app.directives(key, globalDirectives[key]) }) } } export default directives
- 在main.js引入自定义指令
-
// main.js import directives from '@/directives' Vue.use(directives)
vue移动端项目常用的自定义指令
于 2023-05-17 17:50:08 首次发布