Solution Review: Using the Nuxt Image Component
Explore how to implement the Nuxt Image component within a Nuxt 3 project to enable dynamic image selection. Learn to toggle image styling based on user interaction and manage images efficiently using event handling and conditional rendering.
We'll cover the following...
We'll cover the following...
Solution
The solution to the “Using The Nuxt Image Component” challenge is provided below:
<script setup>
const images = [
{
id: 1,
title: "Vue.js logo",
url: "https://upload.wikimedia.org/wikipedia/commons/thumb/9/95/Vue.js_Logo_2.svg/1024px-Vue.js_Logo_2.svg.png?20170919082558",
},
{
id: 2,
title: "Nuxt logo",
url: "https://upload.wikimedia.org/wikipedia/commons/4/45/NuxtJS_Logo.png?20190302014036",
},
{
id: 3,
title: "JavaScript logo",
url: "https://upload.wikimedia.org/wikipedia/commons/3/3b/Javascript_Logo.png?20210407134359",
},
];
const selectedImage = ref(null);
function handleImageClicked(image) {
if (selectedImage.value?.id == image.id) {
selectedImage.value = null;
} else {
selectedImage.value = image;
}
}
</script>
<template>
<ul>
<li v-for="image in images" :key="image.id">
<nuxt-img
:src="image.url"
@click="handleImageClicked(image)"
width="200px"
quality="80"
:style="{
border:
selectedImage?.id === image.id
? '2px solid lightslategrey'
: 'none',
}"
/>
</li>
</ul>
</template>
<style>
ul {
display: grid;
grid-template-rows: repeat(3, 1fr);
grid-template-columns: repeat(3, 1fr);
list-style: none;
}
img {
cursor: pointer;
}
</style>
Implement your code
Explanation
Here is an explanation of the above code solution: ...