Nuxt3自定义404页面使用默认布局时props读取错误求助
解决Nuxt3自定义404页面中"Cannot read properties of undefined (reading 'modeCheckout')"错误
错误原因
在AppBar.vue的模板代码中,你通过props.modeCheckout的方式访问组件属性,但在Nuxt3的<script setup>语法里,defineProps定义的属性会直接暴露到模板作用域中,无需通过props.前缀访问。直接使用props.modeCheckout会导致模板中无法识别props对象,从而抛出该错误。
解决方案
步骤1:修改AppBar.vue的模板代码
将模板中所有props.modeCheckout的引用替换为直接使用modeCheckout:
修改后的AppBar.vue模板部分:
<template> <div class="container"> <div class="app-bar-wrapper p10"> <NuxtLink class="logo-wrapper" to="/"> <img src="/logo.png" alt="Artisan"> </NuxtLink> <div v-if="!modeCheckout" class="search-wrapper"> <Icon name="mdi:magnify" color="black" size="24"/> <input type="text" autocomplete="off" spellcheck="false" placeholder="Search"> </div> <div class="app-bar-actions"> <div v-if="!modeCheckout" :class="['hamburger-wrapper', isClickedHamMenu ? 'close' : '']" @click="toggleMenu"> <span class="child-1"></span> <span class="child-2"></span> <span class="child-3"></span> </div> <div class="icon-wrapper"> <Button icon="mdi:account" fontSize="24px" fontColor="#000" text hoveredBackground="transparent" background="transparent" hoveredColor="#000" padding="0" /> </div> <NuxtLink to="/cart" class="icon-wrapper"> <Button icon="mdi:cart-outline" fontSize="24px" fontColor="#000" text hoveredBackground="transparent" background="transparent" hoveredColor="#000" padding="0" /> <div v-if="basketItemCount>0" class="cart-item-count"> {{basketItemCount}} </div> </NuxtLink> </div> </div> <Menu v-if="!modeCheckout"/> </div> </template>
步骤2(可选优化):简化404组件的布局嵌套
你的自定义404组件中无需嵌套<NuxtLayout>,因为App.vue已经包含了全局布局。修改后的404组件代码:
<script setup> const error = useError(); const handleError = () => { clearError({ redirect: '/', }); }; </script> <template> <div class="prose"> <h1>Dang</h1> <p> <strong>{{ error.message }}</strong> </p> <p>It looks like something broke.</p> <p>Sorry about that.</p> <p> Go back to your <a @click="handleError"> dashboard. </a> </p> </div> </template>
验证修改
重新启动Nuxt3项目,访问不存在的路由触发404页面,此时错误应该消失,404页面会正常渲染包含Header和Footer的默认布局。
内容的提问来源于stack exchange,提问作者Erdem Çağlak
相关产品推荐
相关产品推荐

