自定义指令使用

105 阅读1分钟

自定义指令基本使用

Vue.directive('指令名称', {
    // 会在当前指令作用的dom元素 插入之后执行
    // el 指令所在dom元素
    // bindings 里面是指令的参数信息对象
    inserted(el, bindings) {
        
    }
})

自定义指令-实现图片懒加载

//导入默认图片
import defaultImg from '@/assets/images/200.png'

 Vue.directive('lazy', {
      // inserted () {
      //   console.log(11111)
      // }
      mounted (el, binding) {
        // 浏览器提供 IntersectionObserver
        const observer = new IntersectionObserver(
          ([{ isIntersecting }]) => {
            // console.log(isIntersecting, '====IntersectionObserver')
            if (isIntersecting) {
              console.log(el, binding)
              // 图片加载失败就显示默认图片
              el.onerror = function () {
                el.src = defaultImg
              }
              el.src = binding.value
              // 不在监听dom===stop()
              observer.unobserve(el)
            }
          },
          {
            threshold: 0.01
          }
        )
        // 监听dom
        observer.observe(el)
      }
    })

使用

<img v-lazy="图片地址">

自定义指令-处理图片加载失败

// 定义全局的自定义指令
Vue.directive('imgerror', {
  // el 指令所在的元素
  // binding 指令的相关信息对象, binding.value 指令的值
  inserted(el, bindings) {
    // console.log(el, bindings)
    el.onerror = function() {
      // console.log('图片加载失败了'), 设置备用图片地址
      el.src = bindings.value
    }
  }
})

使用

<img v-imgerror="defaultImg" :src="staffPhoto" class="user-avatar">
  
import Img from '@/assets/common/img.jpg'

data() {
  return {
    defaultImg: Img //默认图片
  }
},