【Vue3】解决 Props 没有默认值而报错的问题

【Vue3】解决 Props 没有默认值而报错的问题

先看代码,封装一个面包屑组件,里面的内容需要动态变化,于是用到了 props:

html 复制代码
"<template>
    <div>
        <el-breadcrumb separator="/" class="ml-12 mt-2">
            <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item><a href="/methods/zuzhi">解决方案</a></el-breadcrumb-item>
            <el-breadcrumb-item>{{ lessons.cargoLessons[props.activeIndex].name }}</el-breadcrumb-item>
        </el-breadcrumb>
    </div>
</template>

<script setup lang="ts">
const props = defineProps({
    activeIndex: Number,
});

const lessons = ...
</script>

出现报错:activeIndex 可能未赋值。

解决方案

使用 Vue3的 withDefaults 方法,给 activeIndex 一个默认值:

html 复制代码
<script setup lang="ts">
import { withDefaults, defineProps } from 'vue'

const props = withDefaults(defineProps<{
    activeIndex: number
}>(), {
    activeIndex: 0 // Assigning a default value of 0
});

const lessons = {
    cargoLessons: [
        ...
    ]
}
</script>

在这个例子中,activeIndex 属性被赋予了一个默认值 0。这意味着如果没有为组件提供 activeIndex 属性,它将自动取值为 0。报错也就解决了。

相关推荐
我不吃饼干9 天前
鸽了六年的某大厂面试题:你会手写一个模板引擎吗?
前端·javascript·面试
涵信9 天前
第一节 布局与盒模型-Flex与Grid布局对比
前端·css
我不吃饼干9 天前
鸽了六年的某大厂面试题:手写 Vue 模板编译(解析篇)
前端·javascript·面试
前端fighter9 天前
为什么需要dependencies 与 devDependencies
前端·javascript·面试
满楼、9 天前
el-cascader 设置可以手动输入也可以下拉选择
javascript·vue.js·elementui
veminhe9 天前
HTML5 浏览器支持
前端·html·html5
前端fighter9 天前
Vuex 与 Pinia:全面解析现代 Vue 状态管理的进化之路
前端·vue.js·面试
嘉琪0019 天前
2025——js 面试题
开发语言·javascript·ecmascript
snow@li9 天前
vue3-ts-qrcode :安装及使用记录 / 配置项 / 效果展示
前端·javascript·vue.js
海天胜景9 天前
vue3 el-table 根据字段值 改变整行字体颜色
javascript·vue.js·elementui