【发布时间】:2021-12-31 13:05:44
【问题描述】:
在过去的 8 个月里,我们使用 vue 3 和 class components 构建了一个项目,但由于它似乎不再维护,我们希望逐渐切换到组合 API,更准确地说是设置脚本语法。
我们目前使用的是 vue3.0.0 和 vue-class-components 8.0.0。
我们的目标是,因为我们必须不断向项目添加新功能,开始使用组合 API 创建新组件,同时保留那些已经使用 vue 类组件编写的组件。而且,随着我们的进展,我们将尝试使用组合 API 重写它们。
我尝试使用 vue 类组件创建一个简单的 HelloWorld 组件:
<template>
<div>
<TestComponent :test="'test string'" />
</div>
</template>
<script lang="ts">
import { Options, Vue } from 'vue-class-component';
import TestComponent from './TestComponent.vue';
@Options({
components: { TestComponent }
})
export default class HelloWorld extends Vue {
}
</script>
并添加一个测试组件:
<template>
<h1>Test composant {{ test }}</h1>
</template>
<script lang="ts">
export default {
name: 'TestComponent',
props: { test: {type: String, required: true }},
setup(props: { test: string }, context: unknown) { console.log(context); return { test: props.test } }
}
</script>
但是,我在代码中遇到了一个错误:在 HelloWorld 中声明 TestComponent 时,编译器告诉我他期待在 TestComponent 中声明的参数“test”:
Argument of type '{ name: string; props: { test: StringConstructor; required: boolean; }; setup(props: { test: string; }, context: unknown): { test: string; }; }' is not assignable to parameter of type 'Component<any, any, any, ComputedOptions, MethodOptions>'.
Type '{ name: string; props: { test: StringConstructor; required: boolean; }; setup(props: { test: string; }, context: unknown): { test: string; }; }' is not assignable to type 'ComponentOptions<any, any, any, ComputedOptions, MethodOptions, any, any, any>'.
Type '{ name: string; props: { test: StringConstructor; required: boolean; }; setup(props: { test: string; }, context: unknown): { test: string; }; }' is not assignable to type 'ComponentOptionsBase<any, any, any, ComputedOptions, MethodOptions, any, any, any, string, {}>'.
Types of property 'setup' are incompatible.
Type '(props: { test: string; }, context: unknown) => { test: string; }' is not assignable to type '(this: void, props: Readonly<LooseRequired<any>>, ctx: SetupContext<any>) => any'.
Types of parameters 'props' and 'props' are incompatible.
Property 'test' is missing in type 'Readonly<LooseRequired<any>>' but required in type '{ test: string; }'.ts(2345)
TestComponent.vue.ts(5, 18): 'test' is declared here.
更新: 我尝试在main.ts中全局注册TestComponent,但是报错还是一样
有没有办法让两者协同工作?
【问题讨论】:
-
不清楚您是否有运行时问题或仅类型问题。如果它是类型,那么您可以使用类型断言将其关闭(以
TestComponent: TestComponent as any开头)。 “我试图在 main.ts 中全局注册 TestComponent” - 如何?我不明白这怎么可能是一样的,因为这种方式类组件不应该有components。
标签: vue.js vuejs3 vue-composition-api vue-class-components