【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。报错也就解决了。

相关推荐
炫饭第一名5 分钟前
速通Canvas指北🦮——基础入门篇
前端·javascript·程序员
王晓枫21 分钟前
flutter接入三方库运行报错:Error running pod install
前端·flutter
符方昊21 分钟前
React 19 对比 React 16 新特性解析
前端·react.js
ssshooter27 分钟前
又被 Safari 差异坑了:textContent 拿到的值居然没换行?
前端
曲折41 分钟前
Cesium-气象要素PNG色斑图叠加
前端·cesium
Forever7_1 小时前
Electron 淘汰!新的桌面端框架 更强大、更轻量化
前端·vue.js
不会敲代码11 小时前
前端组件化样式隔离实战:React CSS Modules、styled-components 与 Vue scoped 对比
css·vue.js·react.js
Angelial1 小时前
Vue3 嵌套路由 KeepAlive:动态缓存与反向配置方案
前端·vue.js
jiayu1 小时前
Angular学习笔记24:Angular 响应式表单 FormArray 与 FormGroup 相互嵌套
前端
jiayu1 小时前
Angular6学习笔记13:HTTP(3)
前端