Reputation: 423
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!
Upvotes: 10
Views: 24065
Reputation: 81
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>
Upvotes: 1
Reputation: 22393
Please try require
<img class="img-time-matters" :src="require(`../assets/time-comparison-${locale}.png`)">
Upvotes: 35