10

I am using vue 2 and vue-cli 3. I am trying to bind the src of an tag to a variable in data.

Specifically I am doing the following:

<img class="img-time-matters" :src="`./../assets/time-comparison-${locale}.png`">

export default {
   name: "home",
   components: {},  
   data() {
       return {
           locale: locale // 'en'
       };
   }
}

The binding works

Using Chrome developer tools and examining the network activity I see that the binding works:

http://localhost:8080/assets/time-comparison-en.png

However the resource is not found.

If I remove data binding at hard code the course path to:

<img class="img-time-matters" :src="`./../assets/time-comparison-en.png`">

Vue resolves the resource link to look for the image at:

http://localhost:8080/img/time-comparison-en.74a6f0ca.png

How do I get the Vue to data bind in such a way that it resolves the binding correctly (i.e. time-comparison-en.74a6f0ca.png).

Thanks!

1
  • Which webpack plugins/loaders are you using? Commented Mar 13, 2019 at 23:59

2 Answers 2

35

Please try require

<img class="img-time-matters" :src="require(`../assets/time-comparison-${locale}.png`)">
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks ittus, much appreciated. I spent a bit of time banging my head against this problem. I saw this solution elsewhere but could not get it to work. I misapplies the require function by using it as follows: <img class="img-time-matters" :src=require("../assets/time-comparison-${locale}.png")> I kept receiving a syntax error. The require function needs to go INSIDE the ". Thanks again.
After a long, long search, the perfect solution, thanks ittus.
1

another alternative solution to fix the issue, is to import the image first as a module before binding to src, here is an example

<script>
import logo from "../assets/logo_800_white_background.png";
export default {
  data() {
    return {
      imgPath: logo,
    };
  },
};
</script>

<template>
  <div class="flex items-center justify-between py-6 max-w-[1155px] mx-auto">
    <div>
      <img
        :src="imgPath"
        alt="logo"
      />
    </div>
    <div class="flex items-center space-x-4">
      <router-link to="/">Home</router-link>
      <router-link to="/about">about</router-link>
      <router-link to="/software">software</router-link>
      <router-link to="/hardware">hardware</router-link>
      <router-link to="/contact">contact</router-link>
    </div>
  </div>
</template>



Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.