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

如何在VueJS 3.0中通过传递函数给defineComponent注册局部组件

使用Vue 3的defineComponent函数式写法注册局部组件

好问题!在Vue 3里用函数式风格的defineComponent注册局部组件,其实和选项式的逻辑是相通的——只需要在函数返回的组件配置对象中添加components字段即可,就像你在旧版语法里做的那样。

具体实现步骤

  1. 先引入需要注册的局部组件和Vue的核心API:
import { defineComponent, ref } from 'vue'
import ComponentA from './ComponentA.vue'
  1. 在defineComponent传入的函数中,把局部组件注册到返回的配置对象里:
const HelloWorld = defineComponent(function HelloWorld() {
  const count = ref(0)

  // 注册局部组件,写法和旧版选项式完全一致
  return {
    count,
    components: {
      ComponentA
    }
  }
})

如果觉得把所有配置都堆在返回对象里不够清晰,也可以提前声明components变量,再一并返回:

const HelloWorld = defineComponent(function HelloWorld() {
  const count = ref(0)
  
  // 提前整理组件注册配置
  const components = {
    ComponentA
  }

  return {
    count,
    components
  }
})

补充说明

本质上,defineComponent的函数式写法返回的对象就是组件的完整选项配置,所以选项式API里支持的所有配置项(比如props、methods、watch等),都可以放到这个返回对象中,和旧版选项式的写法是一一对应的,只是换了一种代码组织方式而已。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 10:52:37