Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Include element once in between v-for iteration

Presently, I have a v-for directive that renders a dozen divs from an array. This array holds organic results from an open source search engine api. All of these organic results have the same look, hence the iteration. On the other hand, I have one div that holds a news result. Right now, the only way to include that result is after the organic results have been rendered and at the end of the list. Is there a way to put this news result at any position in between the organic results without having to split up the organic result array?

Please let me know if this is possible within the framework's capabilities.

current situation

<!--org result-->
<!--org result-->
<!--org result-->
<!--org result-->
<!--org result-->
<!--org result-->
<!--org result-->
<!--...-->
<!--news result-->

what I need

<!--org result-->
<!--org result-->
<!--news result-->
<!--org result-->
<!--org result-->
<!--org result-->
<!--org result-->
<!--org result-->
<!--...-->
like image 725
noam suissa Avatar asked Oct 17 '25 18:10

noam suissa


1 Answers

It's hard to give a code example without the specifics, but I would add a computed property that returns a new array combining both the org results and the news result into a single array.

Then you can iterate over the combined array and use a v-if to select which component to render based on the type (org or news).

Something like this:

<template>
  <ul>
    <!-- NOTE: This assumes isOrg and id - change as needed -->
    <li v-for="item in orgAndNews" :key="item.id">
      <span v-if="item.isOrg">org item: {{ item.title }}</span>
      <span v-else>news item: {{ item.title }}</span>
    </li>
  </ul>
</template>

<script>
export default {
  props: {
    orgResults: {
      type: Array,
      required: true,
    },
    newsResult: {
      type: Object,
      required: true,
    },
  },
  computed: {
    orgAndNews() {
      return [...this.orgResults.slice(0, 2), this.newsResult, ...this.orgResults.slice(2)];
    },
  },
};
</script>
like image 93
David Weldon Avatar answered Oct 20 '25 08:10

David Weldon