Reputation: 146
hope everything is okay.
i am used to react.js but when i try vue things were a bit different in react it's very simple accessing props passed from parent in the child component but in vue i must define each prop to use it.
so i was just wondering if it's possible to pass any prop and use it in the child component without defining it
// parent component
const Parent = () => {
return (
<Child anyprop="propvalue" />
)
}
const Child = (props) => {
return (
<p>{JSON.stringify(props)}</p>
)
}
and that would work
//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>
if i do that in vue i can only see "anyprop" not the "anotherprop" i must define it in the define props block to use it
any ideas what can i do to achieve something like what react.js offers
Upvotes: 0
Views: 2523
Reputation: 222548
All data that isn't defined in props
goes to attributes. Despite the name, they aren't HTML attributes and can have non-string values.
In a template they are available as $attrs
:
<Child :anyprop="$attrs.anyprop" anotherprop="value"/>
A more common case is to pass all attributes instead of enumerating them, this is a counterpart to React {...rest}
:
<Child v-bind="$attrs" anotherprop="value"/>
This may be not needed for root element like Child
because attribute fallthrough is done by default, otherwise inheritAttrs: false
should be used.
This requires Child
to have anyprop
prop declared.
In a script, attributes are available as context.attrs
in setup function and useAttrs
in script setup
, they can be used to compute props for nested elements.
Upvotes: 1