Abdelhamied mostafa
Abdelhamied mostafa

Reputation: 146

vue 3 access props passed from parent component that are not defined in child component

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

in react i can do that

// parent component
const Parent = () => {
  return (
    <Child anyprop="propvalue" />
  )
}
const Child = (props) => {
  return (
    <p>{JSON.stringify(props)}</p>
  )
}

and that would work

in vue i can only use props if i define it like this

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

Answers (1)

Estus Flask
Estus Flask

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

Related Questions