1

There are many questions already asked on how binding image src is not working, and I've gone through them, which mentions to import the image using require. However, my question is a bit different: I am changing the image src based on the current locale the user has selected. I tried binding just a string in src based on currentLocale, but the image is not loading. I also tried require in the binding.

File structure for assets:

+ en
`-- download.jpeg
|
+ fr
`-- download.jpeg

My component:

<template>
  <div>
    <img :src="'../assets/en/' + this.currentLocale + '/download.jpeg'">
  </div>
</template>

<script>
//import { imageSrc } from "@/assets/en/download.jpeg";
export default {
  name: "HelloWorld",
  data() {
    return {
      currentLocale: "en"
    };
  }
};
</script>

codesandbox

1 Answer 1

2

Your src binding has a bug in the path (en is hard-coded):

<img :src="'../assets/en/' + this.currentLocale + '/download.jpeg'">
                      ^^^

But also it should use the require keyword on that path:

<img :src="require('../assets/' + this.currentLocale + '/download.jpeg')">

A couple optimizations:

  • this is unnecessary in the component's template, so you could just use currentLocale instead of this.currentLocale
  • Vue CLI projects provide a path alias for the src directory (i.e., @), so you could use @/assets instead of ../assets

Result:

<img :src="require('@/assets/' + currentLocale + '/download.jpeg')">

Codesandbox seems to exhibit a bug when require-ing image assets, so the code above won't work there. Try it locally in a Vue-CLI generated project.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.