[Vuejs]-V-for for nested object

1πŸ‘

βœ…

v-if and v-for on the same element is bad practice, but it’s not a problem to nest a v-for element inside a v-if element. Use v-if to determine if the product has more inner products (i.e. is an object), then nest a v-for to display those inner products, else just display the current "outer" product

<template>
  <div v-for="(link, product) in products" :key="product">
    <div v-if="isObject(product)">
      <div v-for="(innerLink, innerProduct) in products[product]" :key="innerProduct">
        product: {{ innerProduct }} link: {{ innerLink }}
      </div>
    </div>
    <div v-else>product: {{ product }} link: {{ link }}</div>
  </div>
</template>
<script setup>
const products = {
  Shorts: "/shorts",
  Socks: "/socks",
  Shoes: {
    "Shoes4men": "/shoes4men",
    "Shoes4women": "/shoes4women",
    "Shoes4kids": "/shoes4kids",
  },
};

function isObject(product) {
  return typeof products[product] === "object";
}
</script>

example codesandbox

πŸ‘€yoduh

2πŸ‘

If you want to have a v-if on the same element that you have v-for on it and in other hand you do’nt want to use an element like div, you can use template tag that has v-if, something like that:

<div v-for="(item, itemIndex)" :key="itemIndex">
    <template v-if="isOject(item)">
        <!-- do your job -->
    </template>
    <template v-else>
        <!-- do another job -->
    </template>
</div>

Leave a comment