Vue3 Props沒有默認值但報錯的解決方案
Vue3解決 Props 沒有默認值而報錯的問題
先看代碼,封裝一個面包屑組件,里面的內容需要動態(tài)變化,于是用到了 props:
"<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" rel="external nofollow" >解決方案</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>
出現(xiàn)報錯:activeIndex 可能未賦值。
解決方案
使用 Vue3的 withDefaults 方法,給 activeIndex 一個默認值:
<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。報錯也就解決了。
拓展:vue中props設置默認值
一般情況下
props寫法
props:{
obj: {
type: Object,
default: () => {}
},
arr: {
type: Array,
default: () => []
}
}
但是,如果初始化的時候就使用里面的值,可能會出現(xiàn)沒有該值的情況,此時就會報錯。
應該使用以下有默認值的寫法
props:{
obj: {
type: Object,
default: function () {
return {
obje: ''
}
}
},
arr: {
type: Array,
default: function () {
return []
}
}
}
到此這篇關于Vue3 Props沒有默認值但報錯的解決方案的文章就介紹到這了,更多相關Vue3 Props報錯內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
vue項目中,main.js,App.vue,index.html的調用方法
今天小編就為大家分享一篇vue項目中,main.js,App.vue,index.html的調用方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-09-09
vue 監(jiān)聽鍵盤回車事件詳解 @keyup.enter || @keyup.enter.native
今天小編就為大家分享一篇vue 監(jiān)聽鍵盤回車事件詳解 @keyup.enter || @keyup.enter.native,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-08-08

