Incorporating an image within a v-for loop in Vuetify

I am planning to incorporate images at a later stage, but I am currently utilizing v-for and facing a dilemma of how to seamlessly introduce the image within the loop without disrupting its flow.

<template>
  <v-card>
    <p v-for="item in texts" :key="item.id" class="bm-1">{{ item.text }}</p>
  </v-card>
</template>

<script lang="ts">
import { Vue } from "nuxt-property-decorator";

export default class QuickStart extends Vue {
  texts: any[] = [
    {
      id: 0,
      text: "Text A",
    },
    {
      id: 1,
      text: "Text B",
    },
    {
      id: 2,
      text: "Text C",
    },
  ];
}
</script>

As an illustration, in the provided code snippet, my intention is to insert an image between ids 1 and 2. However, I am unsure how to accomplish this task while still utilizing v-for. If not constrained by this directive, I could have simply added numbers or p tags.

In my attempts, I experimented with adding an image alongside an id and text, but the outcome was as expected - unsuccessful.

Answer №1

Approach to Creating

To construct this, there are several methods you could employ. Ensuring the array is properly organized is crucial. One approach might involve text within certain elements of the array, while images reside in others, and then displaying them sequentially. This would mean that each element would alternate between featuring text and an image.

const { createApp, reactive } = Vue

const app = createApp({
  setup() {
    const list = reactive([{
      id: 1,
      text: `Lorem ipsum dolor sit amet consectetur adipisicing elit. Maxime mollitia,
molestiae quas vel sint commodi repudiandae consequuntur voluptatum laborum
numquam blanditiis harum quisquam eius sed odit fugiat iusto fuga praesentium
optio, eaque rerum!`
    }, {
      id: 2,
      imageSrc: "https://picsum.photos/200/300"
    }, {
      id: 3,
      text: `Lorem ipsum dolor sit amet consectetur adipisicing elit. Maxime mollitia,
molestiae quas vel sint commodi repudiandae consequuntur voluptatum laborum
numquam blanditiis harum quisquam eius sed odit fugiat iusto fuga praesentium
optio, eaque rerum!`
    }])

    return { list }
  }
}).mount('#app')
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="fb8d8e9ebbc8d5c8d5cf">[email protected]</a>/dist/vue.global.prod.js"></script>

<div id="app">
  <div v-for="item of list">
    <div v-if="item.text">{{ item.text }}</div>
    <div v-if="item.imageSrc">
      <img :src="item.imageSrc" />
    </div>
  </div>
</div>

Innovative Approach # 2

An alternative concept involves associating images with specific text items. For instance, having two texts in your array with one linked to an accompanying image:

const { createApp, reactive } = Vue

const app = createApp({
  setup() {
    const list = reactive([{
      id: 1,
      text: `Lorem ipsum dolor sit amet consectetur adipisicing elit. Maxime mollitia,
molestiae quas vel sint commodi repudiandae consequuntur voluptatum laborum
numquam blanditiis harum quisquam eius sed odit fugiat iusto fuga praesentium
optio, eaque rerum!`
    }, {
      id: 2,
      imageSrc: "https://picsum.photos/200/300",
      text: `Lorem ipsum dolor sit amet consectetur adipisicing elit. Maxime mollitia,
molestiae quas vel sint commodi repudiandae consequuntur voluptatum laborum
numquam blanditiis harum quisquam eius sed odit fugiat iusto fuga praesentium
optio, eaque rerum!`
    }])

    return { list }
  }
}).mount('#app')
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d5a3a0b095e6fbe6fbe1">[email protected]</a>/dist/vue.global.prod.js"></script>

<div id="app">
  <div v-for="item of list">
    <div v-if="item.imageSrc">
      <img :src="item.imageSrc" />
    </div>
    <div v-if="item.text">{{ item.text }}</div>
  </div>
</div>

Creative Strategy # 3

If you wish to consistently position an image between particular elements (such as the 1st and 2nd, or 2nd and 3rd), these can be pre-declared in the HTML template utilizing a conditional v-if statement to regulate their appearance:

const { createApp, reactive } = Vue

const app = createApp({
  setup() {
    const list = reactive([{
      id: 1,
      text: `Lorem ipsum dolor sit amet...` // Text content here
    }, {
      id: 2,
      text: `Lorem ipsum dolor sit amet...` // Text content here
    }, {
      id: 3,
      text: `Lorem ipsum dolor sit amet...` // Text content here
    }, {
      id: 4,
      text: `Lorem ipsum dolor sit amet...` // Text content here
    }])

    return { list }
  }
}).mount('#app')
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5f292a3a1f6c716c716b">[email protected]</a>/dist/vue.global.prod.js"></script>

<div id="app">
  <div v-for="item of list">
    <!-- Pre-Declared Image between ID-1 and ID-2 -->
    <img v-if="item.id === 2" src="https://picsum.photos/200/300" alt="" />
    
    <!-- Pre-Declared Image between ID-2 and ID-3 -->
    <img v-if="item.id === 3" src="https://picsum.photos/300/300" alt="" />
    
    <!-- Pre-Declared Image between ID-3 and ID-4 -->
    <img v-if="item.id === 4" src="https://picsum.photos/500/300" alt="" />

    <!-- Display Text Content -->
    <div v-if="item.text">{{ item.text }}</div>
  </div>
</div>

Key Takeaways

In conclusion, achieving the desired result can be approached in numerous ways. The inclusion of images alongside text entries within the array is pivotal, either separately or as pairs for enhanced visual appeal.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a method for viewing or manipulating an object within a JSON file?

Could someone please assist me in accessing the total sum displayed in the chart using console.log? I have tried setting it using "var item": "[[value.sum]]", but it did not work. Any help is appreciated. var chartData1 = []; generateChartData(); func ...

Once the div content is reloaded using AJAX, the refreshed HTML suddenly vanishes

My JS code reloads the div every 2 seconds: var auto_refresh = setInterval(function() { $('#indexRefresh').load('/includes/index_refresh_include.php?_=' + Math.random()); }, 2000); After that, I have an AJAX request that loads mor ...

What steps should be followed to set up Selenium WebDriver to accept command line options using Node.js?

I'm currently working with Selenium WebDriver through Node.js and I have a set of resources that I'm not sure how to interpret for my specific objective (here and here). At the moment, all my tests are running successfully as intended but now I w ...

I'm encountering some issues with routing within Node.js and Express framework

I have developed a single page application (SPA) using React framework. Currently, I am working on creating an API with Express in Node.js for my app. Below is the code snippet of my server: const express = require('express'); const app = expr ...

Issue with MERN stack: User not being saved in mongoDB despite lack of errors

Check out the repository at https://github.com/QexleLLC/Otlic After running the frontend with npm start, and starting the backend with nodemon server, everything appeared to be working fine. However, when I tried signing up by going to localhost:3000/sign ...

Enhancing JavaScript Arrays by incorporating data from a JSON file

Could you kindly advise me on what I might be doing incorrectly here? It seems like a simple issue, but it has taken up the entire day. All I wanted to do was add a value to an array called messages from a JSON file. function get_message(params) { va ...

Retrieve DirectionsResult data from a Google Maps URL

Currently, I am developing an updated tool that can transform Google Maps directions into GPX files. The initial version of this tool is performing quite well: it utilizes the Google Maps Javascript API (v3) to showcase a map on the website, allowing users ...

Build a Search Suggestions feature with Node Package Manager (NPM) and Model-View-Controller (M

Stepping into the exciting world of MVC core and harnessing NPM for JavaScript packages has been a learning curve. However, I've encountered an issue that requires some deliberation on the best course of action for resolution. To provide context, I ha ...

How can I prevent tinymce from stripping out my <link> tag?

I'm having an issue with tinymce. dd<script id="kot-id" src="***insert link here***"></script><div id="kotcalculator"></div><link rel="stylesheet" href="***insert link here***" type="text/css" media="screen" /> It seems ...

Events are not being emitted by Socket.io

I recently started learning about socket.io and began following a tutorial on the socket.io website. I have installed everything correctly, but it seems that the socket is unable to emit the event in the index.html file. Can anyone help me with this? Here ...

Incorporating grids for a flickering drag and drop effect in Javascript

I have been working on developing a selection system for a tilemap image where users can select multiple tiles by dragging the mouse to increase the size of the selection container. However, I've noticed a flickering effect while holding down the mous ...

I'm looking to learn how to efficiently write file chunks from a video upload in Node Js. How can I

My current project involves attempting to stream webcam or audio data to Node.js and save it on disk. The aim is to send the chunks of data to the server as soon as they are available. I have successfully captured the stream using getUserMedia, set up me ...

In JavaScript, find a value in an array and substitute it with the value from the

One of my tasks involves manipulating a string variable in the following manner: domNodes += '<a href="javascript: void(0);" data-role="node_jump" data-node="'+this.tagName.toLowerCase()+'">'+this.tagName + "</a>" + " & ...

CSS / JavaScript Navigation Menu overshadowing Flash content in Firefox

On my website, I have a drop-down menu that was created using CSS and JavaScript. This menu drops down over a Flash animation. Interestingly, in Internet Explorer 6 and 7, the drop-down menus successfully appear over the Flash animation. However, in Mozill ...

Utilizing custom fonts with TinyMCE in VueJS using the tinymce-vue package: A step-by-step guide

I'm having trouble implementing custom fonts from my assets/fonts folder into TinyMCE. The font doesn't seem to render properly, except for in the format selector. Even though the font appears to be applied in certain areas like the title, the co ...

Encountering npm error code ERR_SOCKET_TIMEOUT while attempting to generate a React application

Every time I attempt to create a React app using the command: npx create-react-app chat-app I encounter this error message: Error I have attempted various solutions in an effort to resolve the error: To check if I am behind a proxy, I ran the following ...

Attention all controllers summoned from one AngularJS document

Having recently delved into the world of AngularJS and Ionic, I've exhaustively searched for solutions both on this forum and beyond. Despite my efforts, nothing seems to be working. My goal is to create an application with a homepage featuring a ser ...

Angular: Maximizing Input and Output

I'm having trouble with the function displaying within the input field. My goal is to simply allow the user to enter a name and have it displayed back to them. HTML: <div ng-app = "mainApp" ng-controller = "studentController"> <tr> < ...

Guide on how to submit x-editable input data in a Razor page

When the submit button is clicked, I would like the form to be sent using the post method. Thank you for your assistance. Here is the HTML code: <form method="post" class="form-horizontal editor-horizont ...

What is the best way to implement conditional hook usage in React?

Having two hooks at my disposal, useLocalStorage and useQuery, I find myself wondering about conditionally utilizing one of them based on an input prop. I'm considering writing the following: const [value, setValue] = localStorage ? useLocalStorage() ...