Search code examples
vue.jsvuexvue-dynamic-components

How to append a static components to a dynamic ones in Vue?


What I'm trying to achieve is this: I have a <v-window> parent component that takes <v-window-item> children. The first child loops thru a Vuex getter that returns an object and depending on its content dynamically visualizes cards. However, I have another static component that is like a summary and contains a logout button that I want to append to the last dynamic <v-window> generated from the store. Here's how I've set up my code so far:

<v-window v-model="reportPage">
    <v-window-item v-for="card in getSelectedCard" :key="card.id">
    </v-window-item>
</v-window>

Can someone give me some pointers on how to achieve that? Thanks in advance!


Solution

  • I think there are a few ways to achieve such a thing, the one I would use is conditional rendering based on the current index:

    new Vue({
      el: "#app",
      data: {
        someList: [ "first", "middle", "last" ]
      }
    })
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
    
    <div id="app">
      <ol>
        <li v-for="(item, index) in someList">
          {{ item }}
          <span v-if="index === someList.length - 1">
             - logout button component here
          </span>
        </li>
      </ol>
    </div>

    Of course the content of my v-if could be a prop of your v-window-item:

    <v-window-item v-for="(card, index) in getSelectedCard" :key="card.id" show-logout-button="index === getSelectedCard.length - 1">
    

    Or if you have a slot in your v-window-item:

    <v-window-item v-for="(card, index) in getSelectedCard" :key="card.id">
        <logout-button v-if="index === getSelectedCard.length - 1" />
    </v-window-item>