我试图在 Vue 3 中按名称渲染对象列表,但我不断收到“无法读取未定义的属性(读取“名称”)”错误。
我对Vue还是个新手,我不知道为什么它无法读取对象名称。如果有人可以帮助引导我走向正确的方向,那就太好了。
谢谢
Header.vue
<template>
<header>
<div id="header-content">
<div id="header-left">
<img v-bind:src="require('@/assets/clover.png')">
</div>
<div id="header-center">
<div class="header-link">
<router-link style="color: black; text-decoration: none;" to="/">Home</router-link>
</div>
<div class="header-link dropdown">
<!-- <router-link style="color: black; text-decoration: none;" to="/products">Shop</router-link> -->
<p>Shop</p>
<ul class="dropdown-content">
<li :v-for="category in categories" class="dropdown-link">
{{ category.name }}
</li>
</ul>
</div>
<div class="header-link">
<router-link style="color: black; text-decoration: none;" to="/about">About Us</router-link>
</div>
<div class="header-link">
<router-link style="color: black; text-decoration: none;" to="/faq">FAQ</router-link>
</div>
<div class="header-link">
<router-link style="color: black; text-decoration: none;" to="/contact">Contact Us</router-link>
</div>
</div>
<div id="header-right">
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" aria-hidden="true" width="37" height="37"><path stroke-linecap="round" stroke-linejoin="round" d="M16 11V7a4 4 0 00-8 0v4M5 9h14l1 12H4L5 9z"></path></svg>
</div>
</div>
</header>
</template>
<script>
import { ref } from 'vue';
export default {
name: "Header",
setup() {
let categories = ref([{name: "Test"}, {name: "Test 2"}])
return {
categories
}
}
}
</script>
您可以利用“v-if”指令来确保在渲染列表之前定义变量,如下所示
<ul class="dropdown-content" v-if="categories">
<li v-for="category in categories" class="dropdown-link">
{{ category.name }}
</li>
</ul>