簡體   English   中英

vue 3訪問從父組件傳遞的未在子組件中定義的道具

[英]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>
  )
}

那會奏效

在 vue 中,如果我像這樣定義它,我只能使用道具

//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.attrsuseAttrs中可用,它們可用於計算嵌套元素的 props。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM