gpt4 book ai didi

typescript - 你如何推断​​ Vue 3 组件中的 Prop 类型?

转载 作者:行者123 更新时间:2023-12-05 03:47:41 26 4
gpt4 key购买 nike

如何在vue3的组件中获取props的值对于下面的组件,我想通过defineComponent的泛型参数传递来推断props和data的类型,但是这样做无法获取到props的值。我该如何修改它?

import { defineComponent , Prop, Ref, toRefs} from 'vue'

interface MProps {
day: number
}

interface MData {
day: Ref<number>,
}

export default defineComponent<MProps, MData>({

setup(props, content) {
const { day } = toRefs(props)
console.log('props.day', props.day)

return {
day: day,
}
},

render() {
return <div>
{this.day}
</div>
}
})

最佳答案

您正在使用 the first signature defineComponent 需要一个直接的 setup 函数。但问题是,它没有extend ComponentOptionsBase为您添加一个 render 函数(此类实现仅在其他重载/签名中可用)。

但是,如果您愿意,可以将 JSX 元素作为 RenderFunction 返回有第一个签名;尽管令人遗憾的是,正如在下面的评论中所讨论的那样——这并没有按预期工作(因为父/消费组件传递的 props 实际上是作为 DOM 属性传递的!)。希望我们没有遗漏一些非常明显的东西,比如必须在某处实际定义 Prop ?

export default defineComponent<MProps, MData>(function setup(props) {
const { day } = toRefs(props);

return () => (
<div>{day}</div>
);
})

但是,如果您可以使用第二个签名,则以下方法(使用 Props Annotation )将为您提供相同的类型推断效果,但会牺牲您的结构化合约(接口(interface)) .

import { defineComponent, PropType, toRefs } from 'vue';

type MonthNames = 'January' | 'February' | 'March';

interface ITodo {
done: boolean;
notes: string;
dateCreated: Date;
dateModified: Date;
}

export default defineComponent({
props: {
// We won't have issue with primitive values as they can be automatically inferred
day: Number,

// Here's our challenge. And `PropType` to the rescue!
monthNames: Array as PropType<MonthNames>,

todo: Object as PropType<ITodo>,

todoList: Array as PropType<ITodo[]>,

// Another variation: With custom class
todoList2: class TodoList implements Array<ITodo> {

}
},

setup(props) {
const { day, monthNames, todo, todoList } = toRefs(props);

// If you use VSCode, you should get intellisense with the list of month names
// as soon as you type an opening quote
monthNames.value = 'January';

todo.value.done = true;

todoList.value.push({
done: false
});

return {}
}
});

关于typescript - 你如何推断​​ Vue 3 组件中的 Prop 类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64783108/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com