Embed the component into the array collection

I have an array and I want to display a random component inside it. Specifically, I want to include the FeedbackComponent before the last two objects in the array. This is how it should look like in a schematic representation:

storyObject storyObject storyObject storyObject storyObject feedbackComponent storyObject storyObject

Is there a way to achieve this without changing the original array? I have been searching for a solution similar to rendering inside a component in React.

Here is my PortfolioComponent.vue which contains a few objects from a json data:

<template>
    <ul class="portfolio">
        <story-component
          v-for="story in portfolio"
          :key="story.id"
          :story-name="story.name"
          :story-title="story.title" />
        <li is="feedback-component" class="portfolio__feedback"></li>
    </ul>
</template>

<script>
import portfolio from '@assets/data/portfolio.json';

import StoryComponent from './StoryComponent';
import FeedbackComponent from './FeedbackComponent';

export default {
  components: {
    StoryComponent,
    FeedbackComponent,
  },
  data() {
    return {
      portfolio,
    };
  },
};
</script>

Below is the HTML code of my StoryComponent.vue:

<template>
  <li class="story">
    <span class="story__name">{{ storyName }}</span>
    <span class="story__title">{{ storyTitle }}</span>
  </li>
</template>

I hope this explanation is clear and provides enough information.

Answer №1

To properly position the extra component within the array using the v-for index, you can use the conditional statement

v-if="index === Math.max(0, portfolio.length - 2)"
. If the array contains fewer than 2 items, the feedback component will be placed at the beginning. If the array is empty, nothing will be rendered. Separate handling would be needed for that scenario.

new Vue({
  el: '#app',
  
  data () {
    return {
      portfolio: [
        { id: 1 },
        { id: 2 },
        { id: 3 },
        { id: 4 },
        { id: 5 },
        { id: 6 }
      ]
    }
  }
})
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6513100025574b534b5455">[email protected]</a>/dist/vue.js"></script>

<div id="app">
  <ul>
    <template v-for="(story, index) in portfolio">
      <li 
        v-if="index === Math.max(0, portfolio.length - 2)"
        key="feedback"
      >
        Feedback component
      </li>
      <li :key="story.id">
        Story component {{ story }}
      </li>
    </template>
  </ul>
</div>

I've utilized simple <li> elements for demonstration, but the same approach can be applied with components.

Answer №2

Utilizing computed properties, you have the capability to divide your array into two parts:

<template>
    <ul class="portfolio">
        <story-component
          v-for="story in computedPortfolioBefore"
          :key="story.id"
          :story-name="story.name"
          :story-title="story.title" />

        <li is="feedback-component" class="portfolio__feedback"></li>

        <story-component
          v-for="story in computedPortfolioAfter"
          :key="story.id"
          :story-name="story.name"
          :story-title="story.title" />
    </ul>
</template>

<script>
import portfolio from '@assets/data/portfolio.json';

import StoryComponent from './StoryComponent';
import FeedbackComponent from './FeedbackComponent';

export default {
  components: {
    StoryComponent,
    FeedbackComponent,
  },
  computed: {
    computedPortfolioBefore() {
     if( this.portfolio.length > 2 ) {
       // excludes the last 2 items
       return this.portfolio.slice(0, -2);
     } else {
       return this.portfolio;
     }
    },
    computedPortfolioAfter() {
     if( this.portfolio.length > 2 ) {
       // includes only the last 2 items
       return this.portfolio.slice(-2);
     } else {
       return [];
     }
    }
  },
  data() {
    return {
      portfolio,
    };
  },
};
</script>

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

Trigger the jQuery function based on the ID modification executed by jQuery

Is it possible to change the id of an HTML element using this function? $("#test").attr('id', 'test2'); Here is an example of the code: $("#test").click(function() { $("#test").attr('id', 'test2'); alert(& ...

The functionality of uploading files in Dropzone.js is not supported on Windows operating systems

I am currently working on a file uploader using dropzone functionality. I will share the code with you shortly, but first let me outline the problem: My setup consists of an Ubuntu machine running the server code in node.js using the multer library. The f ...

Nuxt - displaying HTML exclusively on the server side

One issue I am facing is that my page includes a header sourced from a file on the server: data() { return { headerHTML: '' }; }, fetch() { this.headerHTML = fs.readFileSync('./header.html', 'utf8'); } To display th ...

Easily linking a React app to MongoDB

I recently developed a basic react app using 'create-react-app'. The app includes a form, validation, and Bootstrap components. It may not be extravagant, but it functions flawlessly. Furthermore, I registered with MongoDB to obtain a compliment ...

Steps to store chosen option from dropdown list into a database's table

I am currently populating a dropdown list in my PHP file by fetching data from a database. Here is the code snippet: <script type="text/JavaScript"> //get a reference to the select element var $select = $('#bananas'); //reques ...

Submitting Data Forms with AJAX on dynamically loaded webpages

Issue with Form Submission in Ajax-Generated Page I am experiencing an issue with form submission on a page generated within AJAX. The page contains two forms, #form1 and #form2. The jQuery code for submitting the form is as shown below: jQuery("#form1" ...

Delete elements from a dynamic list

I am working with a dynamic array containing chat messages, structured like this: { id:1, message: bla-bla }, { id:2, message: bla-bla }, { id:1, message: bla-bla }, { id:1, message: bla-bla }, { id:3, message: bla-bla }, { id:4, message: bla- ...

Switch between individual highcharts by selecting or deselecting checkboxes

One of the challenges I am facing involves manipulating multiple scatter plots created with highcharts. I have a list of checkboxes, each labeled to correspond with legend identifiers in the highcharts. My goal is to create a dynamic functionality so tha ...

Checking a bcrypt-encrypted password in an Express application

I am encountering an issue with my login password verification code. Even when the correct password is entered, it is not being validated properly. Can anyone provide assistance with this problem? login(req, res) { const { email, pass } = req.body; ...

Oops! Vue.js router configuration is throwing an error because it's unable to read properties of undefined when trying to access 'use'

Description: I have been working on a leaderboard web application using Vue.js. When I tried to launch the server on localhost after finishing my code, I encountered an error. The error message I received is as follows: Uncaught runtime errors: ERROR Cann ...

Retrieve the current time of day based on the user's timezone

Currently, I am working with a firebase cloud function that is responsible for sending push notifications to my app. My main requirement is to send notifications only during the day time. To achieve this, I have integrated moment-timezone library into my p ...

What is the best way to handle the keystroke event in a $.bind method?

I'm struggling with passing a specific keystroke through the bind method. $(document).bind('keyup', event, keyup_handler(event)); This is my attempt at solving it.. Here is the function it should be passed to: var keyup_handler = functio ...

Tips on effectively utilizing a value that has been modified by useEffect

Here is my current code: const issues = ['x','y','z']; let allIssueStatus; let selectedIssueStatus = ''; useEffect(() => { const fetchIssueStatus = async() => { const response = await fetch(&ap ...

What is the maximum allowable size for scripts with the type text/json?

I have been attempting to load a JSON string within a script tag with the type text/json, which will be extracted in JavaScript using the script tag Id and converted into a JavaScript Object. In certain scenarios, when dealing with very large data sizes, ...

Verifying the emptiness of a PHP array using JavaScript

Hey there, I've got a form set up for users to input one or more books into a database. If a user forgets to enter the title when adding just one book, a JavaScript alert pops up reminding them to fill it in. However, if they have two or more books an ...

What is the best way to link my React application with my Express API?

I've been immersed in my react app project for a while now, and I've recently delved into developing a server (using node and express) as well as planning to incorporate a database for it (MongoDB). My client-side react app has been smoothly run ...

Vue allows you to easily generate child div elements within a parent

Having some issues creating a child div with Vue. The code is being placed correctly, but it's being stored as an array. <template> <div class="containers" v-bind:style="{ backgroundColor: pageStyle.backgroundColor, paddingLeft:'5%& ...

Consumer using ActiveMQ-Stomp is not receiving any messages

I attempted to create a JavaScript code for an ActiveMQ subscriber that would subscribe to a specific topic, but unfortunately I am not receiving any messages after establishing the connection. The topic that needs to be subscribed to is COO.2552270450083 ...

JavaScript: Converting an Array to a String

Having trouble making the string method work with an array - it keeps showing up as empty. let url = "https://api.myjson.com/bins/be7fc" let data =[]; fetch(url) .then(response => response.json()) .then(result => data.push(r ...

Having trouble with Ng-repeat not functioning properly on arrays of objects?

I have an array of objects that I fetched from the server. The query is working fine, but when I try to use the ng-repeat directive in my HTML view, nothing is being displayed. Why could this be happening? Here is the JavaScript code: $scope.companyList = ...