Michael Paccione
Michael Paccione

Reputation: 2817

Vue.js Dynamic Image paths after compiling/runtime

I am having a problem setting dynamic image paths with Vue.js. I am using the Vue-Cli to build the project.

I believe the issue is caused because I am referencing image paths dynamically after runtime. Normally it seems the references to my ./assets/ folder are converted into ./img/ after runtime. Since I am changing the url dynamically after load the paths don't appear to work/load. Country is initially set via a store getters but is then v-modeled from a language select dropdown, where the values correspond the the url suffix.

    <div id="flag-container" :style="{ backgroundImage: `url(${src})` }"></div>

    computed: {
            src(){
                return `./assets/flags/flag-${this.country}.png`;
            }
        },

    data() {
        return {
            country: this.$store.getters.language
        }
    }

Inspector shows url change is implemented.

Any recommendation on the best solution for this?

Upvotes: 2

Views: 902

Answers (2)

Michael Paccione
Michael Paccione

Reputation: 2817

Using webpack require context and beforeMount, I was able to store the images in base64 format inside an object. I stored the object and accessed it with a dynamic key. Thanks Max for leading me to the right documentation.

export default {
  beforeMount() {
    var that = this;
    function importAll(r) {
      r.keys().forEach((key) => (that.imgCache[key] = r(key)));
    }

    importAll(require.context("../assets/flags/", true, /\.png$/));
  },
  computed: {
    src() {
      var key = `./flag-${this.country}.png`,
        url = this.imgCache[key];

      return url;
    },
  },
};

Upvotes: 2

ljubadr
ljubadr

Reputation: 2254

Don't use

data() {
    return {
        country: this.$store.getters.language
    }
}

as it will stop being reactive to store changes. Use computed property

<div id="flag-container" :style="{ backgroundImage: `url(${src})` }"></div>

computed: {
    src(){
        return `./assets/flags/flag-${this.country}.png`;
    },
    country() {
        return this.$store.getters.language
    }
},

Upvotes: 0

Related Questions