Reputation: 259
I need to load an image (from my file system and not url) dynamically with vuetify. However, when I bind a path variable in v-img element, vue cannot find it. When I put it statically using the "required" method, it is ok.
How can I choose a dynamic path with vuetify? Is this a problem with the file loader?
I expect to select the image in run time dynamically. For example, if I have "next" button, I want to load the next image. Here is the code in Vue.js
<html>
<v-img
v-bind:src="require(myPath)"
aspect-ratio="1.5"
max-height="500"
contain
/>
</html>
<script>
data: () => ({
mycount: 1,
myPath: "../myimages/2.png"
})
</script>
[Vue warn]: Error in render: "Error: Cannot find module '../myiamges/2.png'" found in ---> at src/App.vue vue.runtime.esm.js:619 Error: "Cannot find module '../imyimages/2.png'" webpackEmptyContext components sync:2 render Gamesheet.vue:30 VueJS 21 run es6.promise.js:75 notify es6.promise.js:92 flush _microtask.js:18 vue.runtime.esm.js:1888
Upvotes: 7
Views: 12259
Reputation: 11
You can try this:
<template>
<div>
<v-img
v-for="(item, i) in data" :key="i"
:lazy-src="`${url_to_bakc + item.img}`"
:src="`${url_to_bakc + item.img}`"
></v-img>
</div>
</template>
<script>
export default {
data() {
return {
url_to_bakc: 'https://mywebsite.com/'
data: [
{label: '...', img: 'img.png'}
]
}
},
}
</script>
Upvotes: 0
Reputation: 11
You can do this too:
<v-img
:src="`${image-variable}`">
</v-img>
This worked in Vuetify 1.5
Upvotes: 1
Reputation: 259
After a long research and tries I found the answer of my own question.
The problem here is with the method "require". It needs to know the folder where the images are, during the compilation, when I use a dynamic path. See here. So giving the path including the file name dynamically won't enable the "require" method to identify the folder only. That was imy interpretation.
So I modifed the code like this and it worked for me:
<html>
<v-img
v-bind:src="require('../myimages/' + myFilename)"
aspect-ratio="1.5"
max-height="500"
contain
/>
</html>
<script>
data: () => ({
mycount: 1,
myFilename: "2.png"
})
</script>
In this case, I could change myFilename in the runtime and it worked as well.
Upvotes: 18
Reputation: 305
Try using computed properties, something like:
<html>
<v-img
v-bind:src="require(imageSrc)"
aspect-ratio="1.5"
max-height="500"
contain
/>
</html>
<script>
data: () => ({
mycount: 1,
myPath: "../myimages/2.png"
}),
computed: {
imageSrc() {
return this.myPath;
}
}
</script>
This will make the imageSrc be a dynamic variable, but you said about clicking a "next" button, this click need to change the "myPath" value then "imageSrc" will change and the v-img will get this new value;
Upvotes: 0