如何在VueJS 3.0中通过传递函数给defineComponent注册局部组件
使用Vue 3的
defineComponent函数式写法注册局部组件 好问题!在Vue 3里用函数式风格的defineComponent注册局部组件,其实和选项式的逻辑是相通的——只需要在函数返回的组件配置对象中添加components字段即可,就像你在旧版语法里做的那样。
具体实现步骤
- 先引入需要注册的局部组件和Vue的核心API:
import { defineComponent, ref } from 'vue' import ComponentA from './ComponentA.vue'
- 在
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
相关产品推荐
相关产品推荐

