index.js 1.9 KB

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