Vue3---报错Uncaught (in promise) TypeError: Cannot read properties of undefined (reading ‘1‘)
问题原因:当goods刚定义时为空对对象, { }.category 的值就为 undefined。解决方法2:v-if手动控制渲染时机,保证只有数据存在才渲染。解决方法1:可选链的语法?
·
问题原因:当goods刚定义时为空对对象, { }.category 的值就为 undefined
解决方法1:可选链的语法 ?.
解决方法2:v-if手动控制渲染时机,保证只有数据存在才渲染
<script setup>
import {getDetail} from "@/apis/detail";
import {onMounted, ref} from "vue";
import {useRoute} from "vue-router";
const goods = ref({})
const route = useRoute()
const getGoods = async () => {
const res = await getDetail(route.params.id)
goods.value = res.result
}
onMounted(() => getGoods())
</script>
<template>
<!-- 方法二 -->
<!--details为goods里的某一个字段-->
<div class="container" v-if="goods.detail">
<el-breadcrumb separator=">">
<el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
<!--
goods一开始是 {}, {}.category -> undefined
解决方法1:可选链的语法 ?.
解决方法2:v-if手动控制渲染时机,保证只有数据存在才渲染
-->
<el-breadcrumb-item :to="{ path: `/category/${goods.category[1].id}` }">{{ goods.category[1].name }}
<!-- 方法一 -->
<!--<el-breadcrumb-item :to="{ path: `/category/${goods.categories?.[1].id}` }">{{ goods.categories?.[1].name }}-->
</el-breadcrumb-item>
<el-breadcrumb-item :to="{ path: `/category/sub/${goods.categories[0].id}` }">{{ goods.categories[0].name }}
<!--<el-breadcrumb-item :to="{ path: `/category/sub/${goods.categories?.[0].id}` }">{{ goods.categories?.[0].name }}-->
</el-breadcrumb-item>
</el-breadcrumb>
</div>
</template>
更多推荐
已为社区贡献4条内容
所有评论(0)