You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue3能否同时使用Composition API与vue-class-components?

解决方案

你遇到的是Vue3 TypeScript类型推导不匹配的问题,非class写法的组件未使用defineComponent包裹时,无法和vue-class-component的类型体系正确适配,按以下方法修改即可兼容:

方法1:为现有Composition API组件补充defineComponent包装

修改TestComponent的script部分,代码如下:

<template>
  <h1>Test composant {{ test }}</h1>
</template>

<script lang="ts">
import { defineComponent } from 'vue'
export default defineComponent({
  name: 'TestComponent',
  props: { 
    test: {
      type: String, 
      required: true 
    }
  },
  setup(props) { 
    // 不需要手动声明props类型,defineComponent会自动从props配置推导类型
    console.log(props.test)
    return { test: props.test } 
  }
})
</script>

修改后vue-class-component组件引入注册时就不会出现类型报错,运行也完全兼容。

方法2:新组件直接用<script setup>语法(更推荐)

3.2及以上版本的Vue3原生支持<script setup>语法,写法更简洁,和class组件的适配性更好,TestComponent可以改写为:

<template>
  <h1>Test composant {{ test }}</h1>
</template>

<script setup lang="ts">
const props = defineProps<{
  test: string
}>()
</script>

这种写法不需要额外注册组件,在class组件内可以直接引入使用,类型自动匹配。

额外建议

你当前使用的Vue3.0.0版本过旧,建议升级到3.2.x以上的稳定版本,对Composition API的类型支持和运行时性能都有明显优化,不会出现额外的兼容问题。

两种写法本身是完全兼容的,修改后你可以正常保留旧的class组件,新功能全部用Composition API开发,后续逐步重构旧组件即可。


内容的提问来源于stack exchange,提问作者ATM

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 22:36:04