directive.js 1002 B

123456789101112131415161718192021222324252627282930313233343536373839
  1. import Vue from 'vue'
  2. import onlyNumber from './onlyNumber'
  3. /**
  4. * 全局注册自定义指令,用于判断当前图片能否加载成功,可以加载成功赋值img的src属性,否则使用默认图片
  5. * 在网络慢的时候,加载图片多的时候,可以达到占位效果
  6. * 使用方法: <img src="默认图片.jpg" v-real-img="真实图片.png"/>
  7. */
  8. Vue.directive('real-img', async function (el, binding) {
  9. let imgUrl = binding.value; // 获取图片地址
  10. if (imgUrl) {
  11. let exist = await imgIsExist(imgUrl)
  12. if (exist) {
  13. el.setAttribute('src', imgUrl)
  14. }
  15. }
  16. })
  17. /**
  18. * 检测图片是否存在
  19. */
  20. let imgIsExist = function (url) {
  21. return new Promise(resolve => {
  22. var img = new Image()
  23. img.onload = function () {
  24. if (this.complete == true) {
  25. resolve(true)
  26. img = null
  27. }
  28. }
  29. img.onerror = function () {
  30. resolve(false)
  31. img = null
  32. }
  33. img.src = url
  34. })
  35. }
  36. Vue.directive('onlyNumber', onlyNumber)