[Vuejs]-Change the CSS if dynamically changing image is loaded in Vue 3

1๐Ÿ‘

โœ…

This is a nice place to use a watcher.

watch: {
    imgURL(newVal, oldVal) {
      if (newVal !== oldVal) this.imgLoaded = false
    }
  }

Hooking to the input event would work too, but there is an edge case where the new value is similar to the old value. If you then set the imgLoaded to false, the CSS class wonโ€™t change to green-bg because the load event does not fire (since the url did not change).

When using a watcher you can compare the old value to the new value and only set imgLoaded to false if the values are different.

Here is the pen.

๐Ÿ‘คgijswijs

1๐Ÿ‘

Add to you input:

<input type="text" v-model="imgURL" @input="updateURL">

and create function on methodth section:

updateURL() {
    this.imgLoaded = false
}
๐Ÿ‘คSkaneris

1๐Ÿ‘

I managed to solve my issue by using the @error method. imgLoaded would be set to false on error and set to true on load.

<div id="app">

    <div :class="imgLoaded ? 'green-bg' : 'red-bg'">
      <img :src=imgURL @load="imgLoaded = true" @error="imgLoaded = false" />
      <br/>
      <input v-model="imgURL" />
    </div>
    
  </div>

This works for the case where the CSS class is changed based on whether the image exists or not.

๐Ÿ‘คveesar

Leave a comment