我尝试编写一个容器组件"A“来布局第三方组件"Tree",为了使用A,我使用"inheritAttrs”来获取“Tree”的所有道具和事件:
<template>
<Tree v-bind="$attrs" />
</template>
<script lang="ts">
export default {
inheritAttrs: true,
};
</script>
<script lang="ts" setup>
import { Tree } from 'ant-design-vue';
import { onMounted, PropType, toRef, unref, ref, toRefs } from 'vue';
function A() {
// this is not working
console.log(props);
}
</script>如何从函数A中的“树”继承一些道具?
发布于 2022-03-22 09:36:07
'InheritAttrs‘
首先,inheritAttrs并不意味着继承道具,inheritAttrs设置为true意味着您自动继承属性(而不是 props ),并将这些属性绑定到组件的根节点。
什么是“属性”?
一些常见的属性是class、style、id、disabled、required和minlength属性等等。基本上,所有本机HTML属性都是由inheritAttrs处理的。
如何在props中访问<script setup>对象
在复合API中,您需要显式地定义 <script setup>中的道具,以便能够使用props对象。
在使用<script setup>的单个文件组件中,可以使用defineProps()宏声明道具:
<script setup>
const props = defineProps(['foo'])
console.log(props.foo)
</script>..。
阅读更多信息:如果我有一个与prop同名的attribute怎么办?
让我们树立一个榜样。您可以在disabled中定义一个名为MyComponent.vue的道具。
MyComponent.vue
<template>
<Tree v-bind="$attrs"/>
</template>
<script setup>
const props = defineProps({
disabled: Boolean,
})
console.log(props.disabled); // this works
</script>..。然后添加像这样的组件,传入disabled。请注意,在这两种情况下,:disabled="true"和disabled的含义是相同的--无论是否定义了道具。
App.vue
<MyComponent disabled />由于您使用defineProps()定义了道具,所以v-bind="$attrs"将不再将disabled作为$attrs对象中的属性。正如文档所解释的那样:
Vue组件需要显式的道具声明,这样Vue知道传递给组件的外部道具应该被视为.
换句话说,如果您不定义props,它们将被视为attributes。
发布于 2022-03-22 09:52:30
您可以使用类型记录和组合API (<script setup lang="ts" />)定义typesafe道具,如:
<script setup lang="ts">
const props = defineProps({
foo: { type: String, required: true },
bar: Number
})
props.foo // string
props.bar // number | undefined
</script>但是,通过泛型类型参数定义纯类型的道具通常要简单得多:
<script setup lang="ts">
interface Props {
foo: string,
bar?: number
}
const props = defineProps<Props>()
props.foo // string
props.bar // number | undefined
</script>发布于 2022-09-16 09:42:29
您还可以使用以下方式:
export default {
...
props:["filterOptions"],
setup(props, context) {
const optionsinProps = props.filterOptions;
}
...
};
https://stackoverflow.com/questions/71569344
复制相似问题