简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM