0👍
The following code will resolve the string inside require to the string you want it to. As far as I am concerned it will not work most of the time, since if the full image path is different, require will not know what files to load.
But since you are lucky and your folder’s path is constant require will load all the files from that folder (‘assets/blogPhotos’) and you can use them dynamically.
<template>
<div class="blog-wrappe">
<img v-if="post.welcomeScreen" :src="require(`../assets/blogPhotos/${post.photo}.jpg`)" alt="">
</div>
</template>
<script>
export default {
name: 'BlogPost',
props: ['post'],
data() {
return {
photo: this.post.photo || 'cover',
}
}
}
</script>
Also if you have assets that have completely different paths, you can do something like this, this also has the added benefit, but it will have the added benefit of not loading unnecessary files from that folder, only the ones you need!
Take a look:
<template>
<div class="blog-wrappe">
<img v-if="post.welcomeScreen" :src="getPhotoUrl(post.photo)" alt="">
</div>
</template>
<script>
import coding from '../asset/blog/coding.jpg';
import coding1 from '../pictures/photos/coding1.jpg';
import coding2 from '../images/some/coding2.jpg';
import coding3 from '../browse/image/coding3.jpg';
export default {
name: 'BlogPost',
props: ['post'],
methods: {
getPhotoUrl(photoKey) {
const availablePhotoUrlsMap = {
coding,
coding1,
coding2,
coding3
}
if (!availablePhotoUrlsMap.hasOwnProperty(photoKey)) {
throw new Error(`photo with key ${photoKey} is not available`);
}
return availablePhotoUrlsMap[photoKey];
}
}
</script>
- [Vuejs]-VueJS – Composition API – How to properly import and read a local JSON file
- [Vuejs]-URL affiliate in a <a href> with Nuxt (vue.js)
Source:stackexchange.com