DEV Community

kareem_sulaimon
kareem_sulaimon

Posted on

How To Import Dynamically Image in Vue Vite

This is a JavaScript function takes a parameter name and returns a URL for an image file with the specified name. It uses the URL constructor to create a new URL object, with the first argument being the path to the image file, which is constructed by concatenating the directory name "./dir/", the name passed as a parameter, and the file extension ".png". The second argument passed to the URL constructor is import.meta.url, which is a property that contains the base URL of the current module.

function getImageUrl(name) {
return new URL(`../assets/images/${name}`, import.meta.url).href
}

By calling the href property of the returned URL object, the function will return a string containing the full URL of the image file, including the protocol (e.g. "https:"), the hostname (e.g. "www.example.com"), and the path to the file.

This function can be used in your Vue component to set the image url. For example, you can create a computed property that returns the import statement for the image you want to use as the background, and then bind that property to the "style" binding of a div element.
Here is an example for static image:
`


setup() {
const getImageUrl{
new URL(../assets/images/image.jpg, import.meta.url)
}

return {
getImageUrl
}
}



:style="{background:`url(${getImageUrl(ImageNow) })` + `no-repeat center center/cover`}">

`

`<br> export default {<br> data () {<br> return {<br> images: [&#39;city.jpg&#39;, &#39;house3.jpg&#39;,&#39;family.jpg&#39;]<br> },</p> <p>methods: {<br> getImageUrl(name) {<br> return new URL(<code>../assets/images/${name}</code>,import.meta.url).href<br> }<br> },<br> computed: {<br> ImageNow () {<br> return this.images[Math.abs(this.currentImage)% this.images.length] <br> }<br> } <br> }<br> `

here is another example:
`


import {ref} from 'vue';

setup() {
const gallery= ref([
'gallery1.jpg' ,'gallery2.jpg',
'gallery3.jpg','gallery 4.jpg',
'gallery5.jpg' ,'gallery6.jpg',
] )

function getImageUrl(name) {
return new URL(../assets/images/${name}, import.meta.url).href
}

return {
getImageUrl , summary
}
}
}

`

Top comments (0)