![](/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.