Nuxt 3 how to use dynamic variable for img src - vue.js

So I'm trying to get an img url from an object and setting is as img src. But it's not working and I do not know why.
My variable looks like this:
const props = defineProps({
about: {
title: String,
text: String,
img: String,
leftSide: Boolean
}
})
const cardImg = '~assets/images/' + props.about.img // prints ~assets/images/image.png
this is what i've tried:
<img :src="cardImg" />
And I've tried to use require() as well:
<img :src="require(cardImg)" />
But when I use require() I am getting this error:
Cannot find module '~assets/images/image.png' Require stack: -
The only way I can set an img src is like this:
<img src="~assets/images/image.png" />
But I want the src to be a variable so its dynamic, do you guys know what I am doing wrong
this is the parent component
<section v-for="info in aboutInfo">
<about-card :about="info"></about-card>
</section>
<script setup>
const aboutInfo = [
{
title: "some title",
text: "some text",
img: "image.png",
leftSide: true
}
]
</script>

Assets folder is for files that can marge with bundle files like css, js. svg. For images, use folder public. If you create folder images there, just use path /images/image.png without /public/ prefix.
<img :src="'/images/image.png'" />

Related

Unable to bind :src property to a dynamic value

In the main App.vue component have an img element with src property hard coded as shown below:
<img
src= './assets/Option01.gif'
alt="Image couln't be loaded"
/>
I'm trying to make this a dynamic parameter where, based on certain conditions the displayed image will change. As shown below, I've refactored the code to bind the src property to a variable:
<img
:src= "image"
alt="Image couln't be loaded"
/>
export default {
name: 'App',
data() {
return {
selectedImage: 0,
images: [
'./assets/Option01.gif',
'./assets/Option02.gif',
'./assets/Option03.gif',
'./assets/Option04.gif',
'./assets/Option05.gif'
]
}
},
computed: {
image(){
return this.images[this.selectedImage]
}
}
}
Unfortunately the console will log the message
'GET http://localhost:8080/assets/Option01.gif 404 (Not Found)'.
Any idea on how to proceed in order to make it work?
As per the info I found in this other post the function require() is needed before the image URL in order to make it work:
<img
:src= "require(image)"
alt="Image couln't be loaded"
/>

img src is not working within v-for loop when using list items in vue js [duplicate]

I got a parent component which sends a data object to the children component like this:
<child object-data=" url: 'url here', title: 'Title'"></child>
Then on my children component, I get this object data by doing:
<script>
export default {
props: [
'objectData'
]
}
</script>
Now, for some reason, I can use title without any problem like this {{ objectData.title }} and shows up.
But when it comes to the URL inside an img tag it's not rendering the image.
I attempted doing the following:
<img :src="objectData.url"/> <--- not rendering
<img v-bind:src="objectData.url"/> <--- not rendering
<img v-bind:src="require(objectData.url)"/> <-- throws a warning error because it's not a path but an object I guess.
<img v-bind:src="{objectData.url}"/> <--- throws an error
<img v-bind:src="{{objectData.url}}"/> <--- throws an error
When I check on the dom element, it doesn't even contain a src attribute afterwards.
If I write down the URL without an object, it works.
<img v-bind:src="src/assets/images/icon.png"/>
But I want my URL to come from a parent component.
Any ideas on how to solve this? I added the url-loader on my webpack file:
{
test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
loader: 'url-loader'
}
I also attempted returning objectData.url from a computed/methods fuction:
computed: {
getImageUrl: function() {
return objectData.url;
}
}
And then use it like :src=“getImageUrl” or :src=“{{getImageUrl}}” and I wasn’t lucky either.
I faced the same issue and i fixed it by using require function :
in the parent component App.vue :
<carousel-posts :posts="posts" />
export default {
name: "app",
data() {
return {
posts: [
{
img: require("./assets/logo.png"),
title: "Title 1",
subTitle: "Sub Title 1",
body:"lorem ipsum ..."
}
...
]
};
}
...
}
in the child component i loop through the posts and bind the image src as follows :
<div class="card-body" v-for="(post,idx) in posts" >
<img class="card-img" :src="post.img" />
...
</div>
<script>
export default {
props: ["posts"],
...
So in your case you should have something like :
<child :object-data="objectData"></child>
...
data(){
return{
dataObject:{
url: require('./assets/someimg.png'),
title: 'Title'
}
}
}
Update :
my project tree :
src
|_assets
| |_logo.png
|_components
| |_CarouselPosts.vue
|_App.vue
Two alternatives:
Static links that vue resolves. But they're src-based and don't work with webpack / file-loader:
<img :src="'../assets/filename.png'"/>
Works with webpack. Note the ".default" at the end:
<img :src="require('../assets/filename.png').default"/>
Documentation relevant effective Nov 2019:
https://github.com/vuejs/vue-loader/issues/1612

Trying to load an image inside a assets/img folder in a v-for, but the images does not load

I'm trying to load the images in the assets/img folder in my vue3 project using a v-for inside a div, but they are not loading, just display my alt.
So, I have a vue component what will display a title and a paragraph and also a image. The images are in the assets/img folder, I'm getting the path of the image with a store that I created. When I try to just put the path of the image like this: src="../assets/img/img2.jpg" the images renders.
Here is 1 of my state in the store.js:
content: [
{
headline: 'Teste',
paragraph: 'this is a paragraph',
img: '#/assets/img/img.jpg'
},]
Here is my template using the v-for:
<template>
<div>
<div
class="slider"
v-for="item, i in content"
:key='i'
>
<h1>{{item.headline}}</h1>
<p>{{item.paragraph}}</p>
<img
:src="item.img"
alt="test"
/>
</div>
</div>
</template>
My setup:
setup () {
const store = useStore()
const content = store.getters.getContent
return { content }
}
I tryed to use :src="require(item.img)" but i got a webpack error by doing this:
Uncaught Error: Cannot find module '#/assets/img/img.jpg' webpackEmptyContext components sync:2
Also tryed to point the folder of the images in the src, :src="#/assets/img + item.img", but it didn't work.
I met this question before.
Maybe the following code could help you.
// create a function in util.js
export const getSrc = ( name ) => {
const path = `/src/assets/img/${name}`
const modules = import.meta.globEager('/src/assets/img/*.jpg')
return modules[path].default
}
// use getSrc in someItem.vue
import { getSrc } from '#/util/util.js'
content: [
{
headline: 'Teste',
paragraph: 'this is a paragraph',
img: getSrc('img.jpg')
}
]

Nuxt.js: How to include local images in Markdown blog content?

I created a blog in Nuxt.js which uses Markdown for my articles. When writing my first article, I realized I can't include images in my markdown article from my assets folder. It only works if it's a link like the example below:
Markdown Image:
How can insert an image in Nuxt.js Markdown from this location? assets/images/blog/trees.png
In your vue files, you can access images in assets folder with:
<template>
<img src="~/assets/your_image.png" />
</template>
In markdown file, you can do the same with Markdown syntax:
![image alt text](~/assets/your_image.png)
But as your files in content folder is independent of webpack, you have to run nuxt generate each time you add a file in assets folder.
More info here:
https://nuxtjs.org/docs/2.x/directory-structure/assets/
https://github.com/nuxt/content/issues/106
place your images in static folder with this path :
static/images/img1.png
In markdown file, use this syntax:
![image alt text](/images/img1.png)
In vue files, use like this :
<template>
<img src="/images/img1.png" />
</template>
or for use with content :
1- in content/articles/new-post.md :
---
title: Title
description: This is description
img: /images/img1.png
alt: Article 1
---
## Example
2- in vue file (pages/index.vue) :
<template>
<div>
<div v-for="article of articles" :key="article.slug">
<h1>{{ article.title }}</h1>
<img
v-if="article.img"
class="h-48 xxlmin:w-1/2 xxlmax:w-full object-cover"
:src="article.img"
/>
</div>
</div>
</template>
<script>
export default {
async asyncData({ $content, params }) {
const articles = await $content('articles', params.slug)
.only(['title', 'description', 'img'])
.fetch()
return {
articles,
}
},
}
</script>
notes :
place your images in static folder for example (static/images/*)
use '/' in start of addresses
true => /images/img1.png
false => images/img1.png
Looks like relative paths are not currently available: https://github.com/nuxt/content/issues/693#issuecomment-750412810
Only absolute paths should work after placing the image in the /static directory
![alt text](/images/blog/trees.png)

Vue 3 Vite - dynamic image src

I'm using Vue 3 with Vite. And I have a problem with dynamic img src after Vite build for production. For static img src there's no problem.
<img src="/src/assets/images/my-image.png" alt="Image" class="logo"/>
It works well in both cases: when running in dev mode and after vite build as well. But I have some image names stored in database loaded dynamically (Menu icons). In that case I have to compose the path like this:
<img :src="'/src/assets/images/' + menuItem.iconSource" />
(menuItem.iconSource contains the name of the image like "my-image.png").
In this case it works when running the app in development mode, but not after production build. When Vite builds the app for the production the paths are changed (all assests are put into _assets folder). Static image sources are processed by Vite build and the paths are changed accordingly but it's not the case for the composed image sources. It simply takes /src/assets/images/ as a constant and doesn't change it (I can see it in network monitor when app throws 404 not found for image /src/assets/images/my-image.png).
I tried to find the solution, someone suggests using require() but I'm not sure vite can make use of it.
Update 2022: Vite 3.0.9 + Vue 3.2.38
Solutions for dynamic src binding:
1. With static URL
<script setup>
import imageUrl from '#/assets/images/logo.svg' // => or relative path
</script>
<template>
<img :src="imageUrl" alt="img" />
</template>
2. With dynamic URL & relative path
<script setup>
const imageUrl = new URL(`./dir/${name}.png`, import.meta.url).href
</script>
<template>
<img :src="imageUrl" alt="img" />
</template>
3.With dynamic URL & absolute path
Due to Rollup Limitations, all imports must start relative to the importing file and should not start with a variable.
You have to replace the alias #/ with /src
<script setup>
const imageUrl = new URL('/src/assets/images/logo.svg', import.meta.url)
</script>
<template>
<img :src="imageUrl" alt="img" />
</template>
2022 answer: Vite 2.8.6 + Vue 3.2.31
Here is what worked for me for local and production build:
<script setup>
const imageUrl = new URL('./logo.png', import.meta.url).href
</script>
<template>
<img :src="imageUrl" />
</template>
Note that it doesn't work with SSR
Vite docs: new URL
Following the Vite documentation you can use the solution mentioned and explained here:
vite documentation
const imgUrl = new URL('./img.png', import.meta.url)
document.getElementById('hero-img').src = imgUrl
I'm using it in a computed property setting the paths dynamically like:
var imagePath = computed(() => {
switch (condition.value) {
case 1:
const imgUrl = new URL('../assets/1.jpg',
import.meta.url)
return imgUrl
break;
case 2:
const imgUrl2 = new URL('../assets/2.jpg',
import.meta.url)
return imgUrl2
break;
case 3:
const imgUrl3 = new URL('../assets/3.jpg',
import.meta.url)
return imgUrl3
break;
}
});
Works perfectly for me.
The simplest solution I've found for this is to put your images in the public folder located in your directory's root.
You can, for example, create an images folder inside the public folder, and then bind your images dynamically like this:
<template>
<img src:="`/images/${ dynamicImageName }.jpeg`"/>
</template>
Now your images should load correctly in both development and production.
Please try the following methods
const getSrc = (name) => {
const path = `/static/icon/${name}.svg`;
const modules = import.meta.globEager("/static/icon/*.svg");
return modules[path].default;
};
In the context of vite#2.x, you can use new URL(url, import.meta.url) to construct dynamic paths. This pattern also supports dynamic URLs via template literals.
For example:
<img :src="`/src/assets/images/${menuItem.iconSource}`" />
However you need to make sure your build.target support import.meta.url. According to Vite documentation, import.meta is a es2020 feature but vite#2.x use es2019 as default target. You need to set esbuild target in your vite.config.js:
// vite.config.js
export default defineConfig({
// ...other configs
optimizeDeps: {
esbuildOptions: {
target: 'es2020'
}
},
build: {
target: 'es2020'
}
})
All you need is to just create a function which allows you to generate a url.
from vite documentation static asset handling
const getImgUrl = (imageNameWithExtension)=> new URL(`./assets/${imageNameWithExtension}`, import.meta.url).href;
//use
<img :src="getImgUrl(image)" alt="...">
Use Vite's API import.meta.glob works well, I refer to steps from docs of webpack-to-vite. It lists some conversion items and error repair methods. It can even convert an old project to a vite project with one click. It’s great, I recommend it!
create a Model to save the imported modules, use async methods to dynamically import the modules and update them to the Model
// src/store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
const assets = import.meta.glob('../assets/**')
Vue.use(Vuex)
export default new Vuex.Store({
state: {
assets: {}
},
mutations: {
setAssets(state, data) {
state.assets = Object.assign({}, state.assets, data)
}
},
actions: {
async getAssets({ commit }, url) {
const getAsset = assets[url]
if (!getAsset) {
commit('setAssets', { [url]: ''})
} else {
const asset = await getAsset()
commit('setAssets', { [url]: asset.default })
}
}
}
})
use in .vue SFC
// img1.vue
<template>
<img :src="$store.state.assets['../assets/images/' + options.src]" />
</template>
<script>
export default {
name: "img1",
props: {
options: Object
},
watch: {
'options.src': {
handler (val) {
this.$store.dispatch('getAssets', `../assets/images/${val}`)
},
immediate: true,
deep: true
}
}
}
</script>
My enviroment:
vite v2.9.13
vue3 v3.2.37
In vite.config.js, assign #assets to src/assets
'#assets': resolve(__dirname, 'src/assets')
Example codes:
<template>
<div class="hstack gap-3 mx-auto">
<div class="form-check border" v-for="p in options" :key="p">
<div class="vstack gap-1">
<input class="form-check-input" type="radio" name="example" v-model="selected">
<img :src="imgUrl(p)" width="53" height="53" alt="">
</div>
</div>
</div>
</template>
<script>
import s1_0 from "#assets/pic1_sel.png";
import s1_1 from "#assets/pic1_normal.png";
import s2_0 from "#assets/pic2_sel.png";
import s2_1 from "#assets/pic2_normal.png";
import s3_0 from "#assets/pic3_sel.png";
import s3_1 from "#assets/pic3_normal.png";
export default {
props: {
'options': {
type: Object,
default: [1, 2, 3, 4]
}
},
data() {
return {
selected: null
}
},
methods: {
isSelected(val) {
return val === this.selected;
},
imgUrl(val) {
let isSel = this.isSelected(val);
switch(val) {
case 1:
case 2:
return (isSel ? s1_0 : s1_1);
case 3:
case 4:
return (isSel ? s2_0 : s2_1);
default:
return (isSel ? s3_0 : s3_1);
}
}
}
}
</script>
References:
Static Asset Handling of Vue3
Memo:
About require solution.
"Cannot find require variable" error from browser. So the answer with require not working for me.
It seems nodejs >= 14 no longer has require by default. See this thread. I tried the method, but my Vue3 + vite give me errors.
In Nuxt3 I made a composable that is able to be called upon to import dynamic images across my app. I expect you can use this code within a Vue component and get the desired effect.
const pngFiles = import.meta.glob('~/assets/**/*.png', {
//#ts-ignore
eager: true,
import: 'default',
})
export const usePNG = (path: string): string => {
// #ts-expect-error: wrong type info
return pngFiles['/assets/' + path + '.png']
}
sources
If you have a limited number of images to use, you could import all of them like this into your component. You could then switch them based on a prop to the component.