![](/img/trans.png)
[英]Child component props are empty though they're passed from a parent component
[英]vue 3 access props passed from parent component that are not defined in child component
希望一切都好。
我習慣於 react.js,但是當我嘗試 vue 時,反應有點不同,訪問子組件中從父級傳遞的道具非常簡單,但在 vue 中,我必須定義每個道具才能使用它。
所以我只是想知道是否可以傳遞任何道具並在子組件中使用它而不定義它
// parent component
const Parent = () => {
return (
<Child anyprop="propvalue" />
)
}
const Child = (props) => {
return (
<p>{JSON.stringify(props)}</p>
)
}
那會奏效
//parent
<template>
<Child anyprop="value" anotherprop="value"></Child>
</template>
<script setup>
const props = defineProps({
anyprop: String
})
//child
<template>
<p>{{props}}</p>
</template>
<script setup>
const props = defineProps({
anyprop: String
})
</script>
如果我在 vue 中這樣做,我只能看到“anyprop”而不是“anotherprop”,我必須在定義道具塊中定義它才能使用它
任何想法我可以做些什么來實現像 react.js 提供的東西
所有未在props
中定義的數據都轉到attributes 。 盡管有名稱,但它們不是 HTML 屬性,並且可以具有非字符串值。
在模板中,它們可用作$attrs
:
<Child :anyprop="$attrs.anyprop" anotherprop="value"/>
更常見的情況是傳遞所有屬性而不是枚舉它們,這是 React {...rest}
的對應物:
<Child v-bind="$attrs" anotherprop="value"/>
這對於像Child
這樣的根元素可能不需要,因為默認情況下會完成屬性fallthrough,否則應該使用inheritAttrs: false
。
這需要Child
聲明anyprop
道具。
在腳本中,屬性在 setup function 和script setup
中的context.attrs
和useAttrs
中可用,它們可用於計算嵌套元素的 props。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.