Caused by a problem in a key, vue related

Before doing a project, you have a problem.

Load is out of the picture are the same as have the cache, and then try to replace it when onload, but later found. Just do not add key attributes, we usually habit for the time plus, but if you write custom components, you will forget to add this property, do diff time, vue that do not change, it will not update . But in fact, it will update just slower.

Two months later, I met. I made a widget compatible avatar:

<template>
  <img 
    src="defalut_url"
    v-betterImage:[url]="url"
    alt="" />
</template>

<script>
let imageIsExist = function(url) {
  return new Promise((resolve) => {
    var img = new Image();
    img.onload = function () {
      if (this.complete == true){
        resolve(true);
        img = null;
      }
    }
    img.onerror = function () {
      resolve(false);
      img = null;
    }
    img.src = url;
  });
};
export default {
  props: ['url'],
  directives: {
    betterImage: {
      inserted: function(el, binding) {
        let imgURL = binding.value; // 获取图片地址
        if (imgURL) {
          imageIsExist(imgURL).then(exist => {
            if (exist)  el.setAttribute('src', imgURL);
          });
        }
      }
    }
  },
}
</script>

There is a reference to the assembly, use no problem at all, but on one page, different components at the same time to spend, even if its URL has changed, or not displayed. I started to think is not the key problem, in another component no problem, because there are key, so it is normal. I debug a while, watching or no problem. I did not expect a key cause, suddenly think, will not be default_url same cause, after I spend key is actually solved.

<template>
  <img 
    src="default_url"
    :key="url"
    v-betterImage:[url]="url"
    alt="" />
</template>

Guess you like

Origin www.cnblogs.com/coolicer/p/12486398.html