hilongjw / vue-lazyload

A Vue.js plugin for lazyload your Image or Component in your application.
http://hilongjw.github.io/vue-lazyload/
MIT License
8.01k stars 868 forks source link

[lazy component]There's a weird problem here, probably a vue render function problem #406

Open tomieric opened 4 years ago

tomieric commented 4 years ago

I created a lazy component

<!-- lazy.vue -->
<lazy-component>
  <v-image />
</lazy-component>

and, Another image component

<script>
export default {
  props: {
    data: {
      type: String
    }
  },

  data() {
    return {
      isLoading: true
    };
  },

  methods: {
    load() {
      const img = document.createElement("img");
      const that = this;
      that.isLoading = true;
      // not working
      img.onload = () => {
        this.isLoading = false;
        console.log(this.isLoading, this) // false, vnode, updated hook has called, but template not changed
      };

      // working
      // img.onload = function () {
      //   that.isLoading = false;
      // };
      img.src = this.data;
    }
  },

  mounted() {
    this.load();
  }
};
</script>

If you use the arrow function, the template cannot be updated

LouWii commented 4 years ago

This is because arrow functions don't have the same scope as an anonymous function. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

This has nothing to do with vue-lazyload.