Vue3 solves the problem of errors reported when there is no default value in Props
First look at the code and encapsulate a breadcrumb component. The contents in it need to be changed dynamically, so we used props:
"<template> <div> <el-breadcrumb separator="/" class="ml-12 mt-2"> <el-breadcrumb-item :to="{ path: '/' }">front page</el-breadcrumb-item> <el-breadcrumb-item><a href="/methods/zuzhi" rel="external nofollow" >Solution</a></el-breadcrumb-item> <el-breadcrumb-item>{{ [].name }}</el-breadcrumb-item> </el-breadcrumb> </div> </template> <script setup lang="ts"> const props = defineProps({ activeIndex: Number, }); const lessons = ... </script>
An error occurred: activeIndex may not be assigned.
Solution
Using Vue3withDefaults
Method, giveactiveIndex
A default value:
<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>
In this example, the activeIndex property is given a default value of 0. This means that if the activeIndex property is not provided to the component, it will automatically take the value of 0. The error will be solved.
Expand: Set default value for props in vue
Under normal circumstances
How to write props
props:{ obj: { type: Object, default: () => {} }, arr: { type: Array, default: () => [] } }
However, if the value inside is used during initialization, there may be no value, and an error will be reported at this time.
The following writing method with default values should be used
props:{ obj: { type: Object, default: function () { return { obje: '' } } }, arr: { type: Array, default: function () { return [] } } }
This is the end of this article about the solution that does not have a default value for Vue3 Props but has an error. For more information about Vue3 Props error reports, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!