index.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. import Lazy from './lazy'
  2. import LazyComponent from './lazy-component'
  3. import LazyContainer from './lazy-container'
  4. import LazyImage from './lazy-image'
  5. import { assign } from './util'
  6. export default {
  7. /*
  8. * install function
  9. * @param {Vue} Vue
  10. * @param {object} options lazyload options
  11. */
  12. install (Vue, options = {}) {
  13. const LazyClass = Lazy(Vue)
  14. const lazy = new LazyClass(options)
  15. const lazyContainer = new LazyContainer({ lazy })
  16. const isVue2 = Vue.version.split('.')[0] === '2'
  17. Vue.prototype.$Lazyload = lazy
  18. if (options.lazyComponent) {
  19. Vue.component('lazy-component', LazyComponent(lazy))
  20. }
  21. if (options.lazyImage) {
  22. Vue.component('lazy-image', LazyImage(lazy))
  23. }
  24. if (isVue2) {
  25. Vue.directive('lazy', {
  26. bind: lazy.add.bind(lazy),
  27. update: lazy.update.bind(lazy),
  28. componentUpdated: lazy.lazyLoadHandler.bind(lazy),
  29. unbind: lazy.remove.bind(lazy)
  30. })
  31. Vue.directive('lazy-container', {
  32. bind: lazyContainer.bind.bind(lazyContainer),
  33. componentUpdated: lazyContainer.update.bind(lazyContainer),
  34. unbind: lazyContainer.unbind.bind(lazyContainer)
  35. })
  36. } else {
  37. Vue.directive('lazy', {
  38. bind: lazy.lazyLoadHandler.bind(lazy),
  39. update (newValue, oldValue) {
  40. assign(this.vm.$refs, this.vm.$els)
  41. lazy.add(this.el, {
  42. modifiers: this.modifiers || {},
  43. arg: this.arg,
  44. value: newValue,
  45. oldValue: oldValue
  46. }, {
  47. context: this.vm
  48. })
  49. },
  50. unbind () {
  51. lazy.remove(this.el)
  52. }
  53. })
  54. Vue.directive('lazy-container', {
  55. update (newValue, oldValue) {
  56. lazyContainer.update(this.el, {
  57. modifiers: this.modifiers || {},
  58. arg: this.arg,
  59. value: newValue,
  60. oldValue: oldValue
  61. }, {
  62. context: this.vm
  63. })
  64. },
  65. unbind () {
  66. lazyContainer.unbind(this.el)
  67. }
  68. })
  69. }
  70. }
  71. }
  72. export {
  73. Lazy,
  74. LazyComponent,
  75. LazyImage,
  76. LazyContainer
  77. }