能否创建含render函数的Vue3 Composable以实现内容渲染?
能否创建带render函数的Vue3 Composable来渲染内容?
当然可以,但你提供的示例存在问题——调用useErrorHandling()后没有将返回的渲染内容整合到组件的渲染流程中,所以页面只会显示"hello",不会出现预期的"world!"。
正确实现方案
方案1:返回渲染函数,通过<component>标签渲染
修改Composable,直接返回一个渲染函数:
// useErrorHandling.js import { h } from 'vue' export function useErrorHandling() { return () => h('div', { class: 'bar' }, 'world!') }
在组件中调用并渲染:
<script setup> import { useErrorHandling } from './useErrorHandling.js' const errorRender = useErrorHandling() </script> <template> hello <component :is="errorRender" /> </template>
方案2:返回组件选项,转为可注册组件使用
保持Composable返回带render的对象,在组件中转为可使用的组件:
// useErrorHandling.js import { h } from 'vue' export function useErrorHandling() { return { render() { return h('div', { class: 'bar' }, 'world!') } } }
组件中使用:
<script setup> import { useErrorHandling, defineAsyncComponent } from 'vue' const ErrorComponent = defineAsyncComponent(() => Promise.resolve(useErrorHandling())) </script> <template> hello <ErrorComponent /> </template>
核心逻辑是:Composable返回的渲染相关内容必须被纳入组件的渲染上下文,要么通过<component>直接渲染渲染函数,要么转为组件实例后使用,否则无法在页面上显示。
内容的提问来源于stack exchange,提问作者BT101
相关产品推荐
相关产品推荐

