Skip to content

How to Import Dynamic Images in Nuxt

Posted on:May 14, 2024 at 03:37 PM

Make sure your images have same file extension, if it is .webp, all the images that you will import should .webp too and store those images in spesific directory.

As example below, there are three images with the same file extension and located in the same directory client

files and directory

In the Nuxt components, import filename from pathe/utils it is already installed in Nuxt, you don’t need to install it again manually using npm.

Then, use glob to get the file of images that will imported, here I declare it with also glob variablhere I declare it with also glob variable.

After that create object filter to get images based on filename.

<script setup lang="ts">
import { filename } from "pathe/utils";

const glob = import.meta.glob("@/assets/images/header/*.jpg", { eager: true });

const images = Object.fromEntries(
  Object.entries(glob).map(([key, value]) => [
    filename(key),
    (value as unknown as any).default,
  ]),
);

</script>

<template>

</template>

And let’s say we have users data and want to display the images of the users based on the name.

<script setup lang="ts">
import { filename } from "pathe/utils";

const glob = import.meta.glob("@/assets/images/header/*.jpg", { eager: true });

const images = Object.fromEntries(
  Object.entries(glob).map(([key, value]) => [
    filename(key),
    (value as unknown as any).default,
  ]),
);

const users = ref([
    {
        name: 'yuliana',
    },
    {
        name: 'agus',
    },
    {
        name: 'melissa'
    }
])

</script>

<template>

</template>

Call the images and passed name of user to get the file from glob.


<script setup lang="ts">
import { filename } from "pathe/utils";

const glob = import.meta.glob("@/assets/images/clients/*.jpg", { eager: true });

const images = Object.fromEntries(
  Object.entries(glob).map(([key, value]) => [
    filename(key),
    (value as unknown as any).default,
  ]),
);

const users = ref([
  {
    name: "yuliana",
  },
  {
    name: "agus",
  },
  {
    name: "melissa",
  },
]);
</script>

<template>
  <p>Images from freepik</p>

  <div class="container mx-auto mt-12">
    <div class="grid grid-cols-3 gap-3">
      <div v-for="(user, index) in users" :key="index">
        <img class="h-[300px] object-cover" :src="images[user.name]" />
        <div class="text-center">{{ user.name }}</div>
      </div>
    </div>
  </div>
</template>

And here’s the result

result of import images dynamically in nuxt