Guide on changing the order of Vue sibling components when rendering a shared array within a parent component list

Currently facing a unique challenge and seeking input:

Within the 'App', utilize 'TestListItem' for odd item indexes and 'TestListBetterItem' for even indexes. The same index must be used for both components.

Initial attempts involved setting keys for each child component as odd and even, resulting in a duplicate key error. Looking to pass alternating values from two child components into a common parent component. Below is the complete code snippet:

App.vue

    <template>
  <div id="app">
    <test-list-item>
    </test-list-item>
    <test-list-better-item>     
    </test-list-better-item>
  </div>
</template>

          <!-- <template #title>
            I AM A HEADER
          </template> -->
          <!-- <template #footer>
          I AM A FOOTER
          </template> -->

<script>
import { TestBetterList, TestListItem, TestListBetterItem } from './components';


export default {
  name: 'App',
  components: { TestBetterList, TestListItem, TestListBetterItem },
  data() {
    return {
      items: ['better-item-1',  'better-item-2', 'better-item-3']
    };
  },
  //   watch: {
  //       'better-item-1': {
  //     handler: 'oddMethod',
  //     immediate: true,
  //     deep:true
  //   },
  //       'better-item-2': {
  //     handler: 'evenMethod',
  //     immediate: true,
  //     deep: true
  //   },
  //       'better-item-3': {
  //     handler: 'oddMethod',
  //     immediate: true,
  //     deep: true
  //   },
  // },
  methods: {

  }
};
</script>

<style lang="scss">
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

TestListItem.vue

    <template>
  <div class="test-list-item">
        <template v-for="(item, index) in items">
      <slot>
        <div :key="index">{{ item }}</div>
      </slot>
    </template>
  </div>
</template>

<script>

export default {
  name: 'test-list-item',
  props: {

  },
  data() {
    return {
      items: ['better-item-1',  'better-item-2', 'better-item-3']
    };
  },
  computed: {
   
},
  mounted() {
  },
  created() {},

    //   methods: {
    //     oddMethod: function () {
    //     items[0]
    //   }
    // }

};
</script>

<style scoped lang="scss">
.test-list-item {
  color: purple
}


</style>

TestListBetterItem.vue

    <template>
  <div class="test-list-better-item">
    <template v-for="(item, index) in items">
      <slot>
        <div :key="index">{{ item }}</div>
      </slot>
    </template>

  </div>
</template>

<script>

export default {
  name: 'test-list-better-item',
  props: {

  },
  data() {
    return {
      items: ['better-item-1',  'better-item-2', 'better-item-3']
    };
  },
  computed: {
   
},
  mounted() {
  },
  created() {},

    //   methods: {
    //     evenMethod: function () {
    //     items[0]
  //   }
};

</script>

<style scoped lang="scss">
.test-list-better-item {
  color: rgb(255, 145, 0)
}


</style>

Answer №1

It appears that the task at hand involves conditionally rendering two different types of list items rather than creating two separate lists. The components TestListItem and TestListBetterItem represent individual list items, while the actual array with the list resides in the App component. To tackle this, I suggest creating distinct components for each item type and utilizing v-if and v-else directives to determine which component to render based on the index of the list item.

<template> 
  <div id="app"> 
    <ul id="test-list"> 
      <li v-for="(listItem,listItemIndex) in testList"> 
         <TestListItem v-if="listItemIndex % 2 === 0" /> 
         <TestListBetterItem v-else /> 
      </li> 
    </test-list> 
  </div> 
</template> 

I have also provided a StackBlitz link for your convenience (I used Vue 3, but it can be easily converted back to Vue 2):

VIEW CODE HERE

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

Detecting click events in D3 for multiple SVG elements within a single webpage

My webpage includes two SVG images inserted using D3.js. I am able to add click events to the SVGs that are directly appended to the body. However, I have encountered an issue with another "floating" div positioned above the first SVG, where I append a dif ...

Javascript generates a mapping of values contained within an array

In my current project, I am developing a feature that allows users to create customizable email templates with placeholder tags for content. These tags are structured like [FirstName] [LastName]. My goal is to brainstorm the most effective method for crea ...

Incorporating Stripe into your Next.js 13 application: A step-by-step guide

Struggling to incorporate Stripe into my Next.js 13 app for a pre-built checkout form. So far, all attempts have fallen short. Seeking assistance from anyone who has conquered this integration successfully. Any tips or guidance would be highly valued. Pl ...

Ways to enhance the efficiency of this javascript duplicates

I recently wrote this JavaScript code but, as I am still in the early stages of learning, I am struggling to optimize it efficiently. I ended up duplicating the code for each if statement. $(function() { var lang = $(".lang input[type='checkbox&a ...

Locate all posts associated with the specified User ID

Using mongoose, I am able to populate the "Post Schema" with relevant information about users who create the posts. postModule.js const mongoose = require('mongoose'); const postSchema = mongoose.Schema({ title:String, description:String, date ...

Tips on verifying if user x has sent over two messages in the chat and concealing their identity

I have a JavaScript chat application that is causing me some trouble. I recently implemented a feature to display user names on top of messages, and while it works well for the first message, I am struggling to hide the user's name when they send subs ...

What could be the reason for the appearance of Next.js compile indicator in my final production build?

Upon completing the development and deployment of a Next.js website, I observed that the black compile indicator continued to appear in the bottom-right corner of my browser, similar to its presence during local development. The indicator can be viewed he ...

Parse the JSON data response as needed in ReactJS

var mydata = [ { source: 11, Registernumber: ">RT-113, <RT-333", jul1: 1004 }, { source: 11, Registernumber: ">RT-113, <RT-333", jul2: 1234 }, // Rest of the data entries... ]; Can we transform the above JSON ...

Navigating through a JSON dictionary in Svelte: A step-by-step guide

When working with Svelte, the #each construct allows for easy iteration over array-like objects. But what if you have a JSON dictionary object instead? Is there a way in Svelte to iterate over this type of object in order to populate a dropdown menu? The ...

Experiencing difficulty in successfully updating a React child component when the prop passed from the parent component is

In the backend implementation, I have successfully set up a socket.io, Node, Express configuration that has been tested to work correctly. It is emitting the right number of broadcasts to the appropriate client using socket.emit("team_set", gameI ...

JavaScript code that displays values that are not equal

Here is a code snippet that checks whether two arrays of objects are equal or not. How can we enhance this code to log which answer is not matching? The structure of the arrays: arrayA represents user answered questions, while arrayB contains correct answ ...

Adding a class to unhovered elements with jQuery/JS: a step-by-step guide

I have a variety of elements that are almost working how I want them to. There are four divs in total. Depending on the URL visited, I want a specific div to be fully transparent/active. The next div in line should animate in and out of transparency simul ...

Customize the focus function for an individual element

I am working on a custom component that needs to seamlessly integrate with the native blur and focus functions. My goal is to override these functions in order to achieve the specific functionality I need. Currently, I have managed to override the prototy ...

Pagination Bug: Index Incorrectly Grabbed Upon Navigating to Next Pages

I encountered an issue with my paginated article list (105 articles with 10 per page). Everything works fine on the first page, but when I click on an article from page 2 onwards, it takes me to the index of the very first article in the array. <div cla ...

Guide to rendering pages in SSR mode in NextJS on a specific environment and serving static pages on a different environment

I am facing a challenge with my setup where I have a Strapi backend deployed on the environment I manage, and a NextJS frontend hosted on Vercel. On the other hand, my client has the same Strapi backend code running on Google Cloud and the frontend code ho ...

Fixed position toolbar within a container positioned beside a dynamically sized sidebar navigation

I'm trying to figure out how to create a fixed toolbar that fills the remaining width of the page when a side nav is collapsible. Setting the width to 100% causes it to overflow the page due to the dynamic nature of the side nav. Using calc() isn&apos ...

The process of examining a function that includes the invocation of an additional API function in a NodeJS environment

I'm faced with a situation where I have a nested function inside another function. The second function is responsible for making an API call. However, in order to write a unit test for this scenario, I need to avoid actually making the real API call a ...

JavaScript, JQuery, and the Observer Design Pattern

Currently, I am in the process of developing a third-party application specifically for certain websites using Jquery. Lately, I have incorporated rx.Observable into my project. However, grasping the utilization of this new JS library has proven to be qui ...

What is the best way to transfer an element and all its children to another div without losing any jQuery functionality?

At first, sharing an example of the JavaScript and HTML from my page is challenging because I couldn't make it work on JSfiddle. The issue I'm facing involves jQuery on a page where I've created two tabs. Essentially, it's the same con ...