javascript v-for用于嵌套对象

js5cn81o  于 2023-04-28  发布在  Java
关注(0)|答案(1)|浏览(146)

尝试为嵌套对象执行v-for

const products = {
  Shorts: "/shorts",
  Socks: "/socks",
  Shoes: {
    "Shoes4men": "/shoes4men",
    "Shoes4women": "/shoes4women",
    "Shoes4kids": "/shoes4kids",
  },
}

在frontend中:

<div v-for="(link, product) in products" :key="product" :value="link">
{{ product }} {{ link }}
</div>

这适用于外部链接(短裤,袜子,鞋子),但如何显示Shoes4menShoes4womenShoes4kids文本和链接下的Shoes类别与v-for?我在同一个元素中尝试了v-ifv-for,但没有成功(我读到的似乎也是不好的做法)。

bvjxkvbb

bvjxkvbb1#

在同一个元素上使用v-if和v-for是不好的做法,但是在v-if元素中嵌套一个v-for元素并不是问题。使用v-if来确定乘积是否具有更多内积(即即是一个对象),然后嵌套一个v-for来显示那些内积,否则只显示当前的“外”积

<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

相关问题