欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Vue3 Props沒有默認(rèn)值但報(bào)錯(cuò)的解決方案

 更新時(shí)間:2024年04月09日 09:28:39   作者:正宗咸豆花  
這篇文章主要介紹了Vue3 Props沒有默認(rèn)值但報(bào)錯(cuò)的解決方案,文中通過代碼示例給大家講解的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作有一定的幫助,需要的朋友可以參考下

Vue3解決 Props 沒有默認(rèn)值而報(bào)錯(cuò)的問題

先看代碼,封裝一個(gè)面包屑組件,里面的內(nèi)容需要?jiǎng)討B(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)報(bào)錯(cuò):activeIndex 可能未賦值。

解決方案

使用 Vue3的 withDefaults 方法,給 activeIndex 一個(gè)默認(rèn)值:

<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>

在這個(gè)例子中,activeIndex 屬性被賦予了一個(gè)默認(rèn)值 0。這意味著如果沒有為組件提供 activeIndex 屬性,它將自動(dòng)取值為 0。報(bào)錯(cuò)也就解決了。

拓展:vue中props設(shè)置默認(rèn)值

一般情況下

props寫法

props:{
	obj: {
		  type: Object,
		  default: () => {}
	},
	arr: {
		type: Array,
		default: () => []
	}
}

但是,如果初始化的時(shí)候就使用里面的值,可能會(huì)出現(xiàn)沒有該值的情況,此時(shí)就會(huì)報(bào)錯(cuò)。

應(yīng)該使用以下有默認(rèn)值的寫法

props:{
	obj: {
		  type: Object,
		  default: function () {
		  	return {
				obje: ''
			}
		  }
	},
	arr: {
		type: Array,
		default: function () {
		  	return []
		  }
	}
}

到此這篇關(guān)于Vue3 Props沒有默認(rèn)值但報(bào)錯(cuò)的解決方案的文章就介紹到這了,更多相關(guān)Vue3 Props報(bào)錯(cuò)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論