Vue.js src searching localhost instead of file system

Viewed 40

I have an image whose src I'm trying to change when it is clicked.

<b-img :id="favorite" src="~/static/svg/favorite.svg" @click="iconClicked(favorite)" right />

And down under export default, I have

methods: {
        iconClicked(name: any) {
            (<HTMLImageElement> document.getElementById(name))!.src="~/static/svg/favoriteAlternate.svg";
        }
    }

When I run my code at localhost:3000, I get a 404 error, and the code appears to be searching localhost:3000/~/static/svg/favoriteAlternate.svg instead of my local file system.

Why might this be? What should I do to fix this?

Thanks!

1 Answers

There's a couple of things wrong here.

First, you shouldn't be manually interacting with the DOM like that – Vue "owns" the DOM and you should leave it to Vue to change.

When Vue compiles the template, it treats the src attribute specially by loading the file on disk it refers to through webpack. But then when you manually change the element's src attribute like that, the new file it references was never bundled by webpack so it won't load.

You need to require/import both images so they get bundled. Then swap between them using a binding on the src attribute.

Something like:

<img :src="src">
// These are not javascript files, however webpack will bundle them
// and export the correct src you should use to refer to them
import FavoriteImage from '~/static/svg/favorite.svg'
import FavoriteAltImage from '~/static/svg/favoriteAlternate.svg'

export default {
  data() {
    return {
      src: FavoriteImage,
    }
  },

  methods: {
    iconClicked() {
      this.src = FavoriteAltImage
    }
  }
}
Related