在过去的8个月中,我们使用vue 3和类组件构建了一个项目,但由于它似乎不再被维护,我们希望逐步切换到composition,更确切地说是使用安装脚本语法。
我们目前正在使用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>但是,我的代码中出现了一个错误:当在TestComponent中声明HelloWorld时,编译器告诉我,他期待在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.更新:我尝试在TestComponent中全局注册main.ts,但是错误仍然是相同的。
有办法让这两个人一起工作吗?
发布于 2021-11-22 02:03:12
一个问题是您的props声明是不正确的。它应该是:
// ❌ invalid
// props: {
// test: String,
// required: true
// },
props: {
test: {
type: String,
required: true
}
},此外,您不需要键入setup()的参数,因为它们通常是从defineComponent()实用程序中推断出来的,启用类型推理在Vue组件中是这样的:
// export default {
// setup(props: { test: string }, context: unknown) { /*...*/ }
// }
import { defineComponent } from 'vue'
export default defineComponent({
setup(props, context) { /*...*/ }
})发布于 2021-11-22 01:54:33
请注意,:test是v-bind:test的语法糖,这意味着如果您没有用于:test的反应性变量绑定,则应该使用test。见下文:
// note there is no colon before test, which means you are just passing a constant string.
<TestComponent test="test string" />https://stackoverflow.com/questions/70057164
复制相似问题