DEV Community

Cover image for How To Dynamically Import Image in Vue Vite
kareem_sulaimon
kareem_sulaimon

Posted on

How To Dynamically Import Image in Vue Vite

The JavaScript function below 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.

You can read more about importing statics assets at
https://vitejs.dev/guide/assets.html

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:

<template>
      <img :src="getImageUrl(img )">
    </div>
</template>

<script>
 setup() {
const getImageUrl{
    new URL(`../assets/images/image.jpg`, import.meta.url)
      } 
return {
getImageUrl 
}
}
</script>
Enter fullscreen mode Exit fullscreen mode

Here is an example for dynamic image using option api:

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

<script>
  export default {
    data () {
      return {
        images: ['city.jpg', 'house3.jpg','family.jpg'],
         currentImage: 0,
         interval: null
 }
},

  methods: {
  changeImage () {
  this.interval = setInterval(() => {
  this.currentImage++
  }, 10000);
    },

   getImageUrl(name) {
     return new URL(`../assets/images/${name}`,import.meta.url).href
      }
  },
 computed: {
      ImageNow () {
      return this.images[Math.abs(this.currentImage)% this.images.length] 
      }
  } 
}
</script>`

Enter fullscreen mode Exit fullscreen mode

With Dynamic URL & absolute Path using composition api:

<template>
 <div class="gallery">
        <img v-for="img in gallery" :key="img " :src=" getImageUrl(img )">
    </div>
</template>

<script>
import {ref} from 'vue';

export default {
 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 
}
}
}
</script>

Enter fullscreen mode Exit fullscreen mode

Summary

It's important to declare the getIamgeUrl function in script. Then pass parameters from data. The parameters(image URL) can either be loop using Vue v-for, computed or pass directly incase of single image path.
Read more about handling statics assets at
https://vitejs.dev/guide/assets.html

Top comments (0)