image.png
全局指令在main.js中定义
image.png
image.png
image.png
全局自定义指令原本都是要写到main.js中的,但是如果全局自定义指令比较多的话,都直接写到main.js中,也不好, 这个时候,就需要以插件的格式定义全局指令

以插件的方式定义全局指令

  1. import { useIntersectionObserver } from '@vueuse/core'
  2. import defaultImage from '@/assets/images/200.png'
  3. const myDirective = {
  4. install (app) {
  5. app.directive('imgLazy', {
  6. // 省略其他生命周期钩子函数
  7. // el: 使用了指令的dom
  8. // binding.value: v-指令名="binding.value就是这里表达式的值"
  9. mounted (el, binding) {
  10. el.src = defaultImage
  11. const { stop } = useIntersectionObserver(el,
  12. ([{ isIntersecting }], observeDom) => {
  13. // 如果isIntersecting为true
  14. if (isIntersecting) {
  15. stop()
  16. el.src = binding.value
  17. el.onerror = function () {
  18. el.src = defaultImage
  19. }
  20. }
  21. }, { threshold: 0 })
  22. }
  23. })
  24. }
  25. }
  26. export default myDirective
  27. //然后在main.js中导入这个页面插件
  28. import directives from '@/directives/index.js'
  29. // import defineDirective from '@/directives'
  30. const app = createApp(App)
  31. app.use(store).use(router).use(components).use(directives).mount('#app')

image.png