Vue 3如何通过编程方式向子组件传递Props(非父模板方式)
编程式向Vue子组件传递Props(无需模板)
当然可以通过编程方式在父组件脚本中传递props给子组件,核心是使用Vue的h()渲染函数(或createVNode)来创建子组件实例并传入props,无需在模板中声明组件标签。
方法1:用渲染函数替代模板渲染子组件
修改父组件代码如下,直接在脚本中定义渲染逻辑并传递props:
// Parent component <script setup lang="ts"> import { h } from 'vue' import ChildComponent from './ChildComponent.vue' // 定义要传递的props值 const componentId = 'user-profile-1001' // 创建子组件的虚拟节点(VNode),传入props const renderChild = () => h(ChildComponent, { componentId }) </script> <template> <!-- 调用渲染函数渲染子组件 --> <renderChild /> </template>
方法2:动态创建并挂载子组件到指定DOM
如果需要完全脱离模板控制,可直接创建子组件实例并挂载到页面指定元素:
// Parent component <script setup lang="ts"> import { createApp, h } from 'vue' import ChildComponent from './ChildComponent.vue' const componentId = 'dynamic-widget-2002' // 获取挂载目标DOM元素 const mountTarget = document.getElementById('child-container') if (mountTarget) { // 创建子组件实例并传递props,挂载到目标元素 createApp(h(ChildComponent, { componentId })).mount(mountTarget) } </script> <template> <!-- 挂载目标容器 --> <div id="child-container"></div> </template>
方法3:Vue3.3+ 用defineRender简化渲染逻辑
Vue3.3及以上版本可使用defineRender直接定义组件的渲染内容,无需额外声明渲染函数:
// Parent component <script setup lang="ts"> import { defineRender, h } from 'vue' import ChildComponent from './ChildComponent.vue' const componentId = 'simplified-render-3003' // 直接定义组件的渲染输出 defineRender(() => h(ChildComponent, { componentId })) </script> <!-- 模板可留空 --> <template></template>
以上三种方式都能实现在父组件脚本中传递componentId props,无需在模板中编写子组件标签并绑定props。
内容的提问来源于stack exchange,提问作者Joseph Prosper
相关产品推荐
相关产品推荐

