Search code examples
laravelvuejs2vuetify.jsbelongs-to

Overwrite template slot dynamically


Fetching some headers config from a belongsTo() relation from Laravel. The responses looks like this:

API Response

My Vuetify data table config is this one:

    <v-data-table
            :headers="newHeaders"
            :items="products"
            item-key="name"
        >
      <template v-slot:header.stocks.0.pivot.quantity="{ header }">
        {{ header.text }}
        <v-icon>
          mdi-pencil-outline
        </v-icon>
      </template>
   </v-data-table>

I just want to use the slot to add my icon 'dynamically' to all 'Stock' headers adding (Could be 1, 2 3 or more headers).

How can I achieve this feature? I mean, right now is statically because if another stock is added I have to use <template v-slot:header.stocks.1.pivot.quantity="{ header }"> to do it.

Edited: This is how the table looks like:

Mockup


Solution

  • I use a solution from this answer: Same slot content for multiple template slots It was a kind of gorgeous and this is my solution:

    Template tag

      <v-data-table
            :headers="newHeaders"
            :items="products"
            item-key="name"
        >
      <template 
         :slot="slotName"
         slot-scope="props"
         v-for="slotName in pivotNames">
        {{ props.header.text }}
        <v-icon>
          mdi-pencil-outline
        </v-icon>
      </template>
    

    Script tag

      export default {
        name: "Product",
        data() {
            return {
              newHeaders: [...],
              products: [...],
              stockHeaders: [], //Have stock headers info
              pivotNames: [] //Used in the v-for
            }
        },
        methods: {
            getPivotHeaders() {
                const self = this;
    
                this.stockHeaders.forEach(function(stock, index) {
                    let indexFound = stock["value"].includes("pivot.quantity");
    
                    if (indexFound) {
                        self.pivotNames.push("header." + stock["value"]); //Create name for slot template
                    }
                });
            }
        }