Vue2中如何实例化函数式组件?为何用this.$props而非组件props?
函数式组件JS实例化及props传递问题解答
一、函数式组件在JS中实例化的正确方式
函数式组件本身是无状态、无实例的,本质就是一个返回虚拟节点(VNode)的函数,所以Vue.extend()(用于创建有状态组件构造器的方法)对它完全无效。正确的做法是通过Vue实例的render函数直接渲染,或者用h(Vue2)/createVNode(Vue3)生成虚拟节点后挂载,举个Vue2的示例:
import Vue from 'vue' import MyFunctionalComponent from './MyFunctionalComponent.vue' // 创建Vue实例并挂载到指定节点 const vm = new Vue({ el: '#target-container', // 可选:继承函数式组件的props定义,让当前实例能接受对应属性 props: MyFunctionalComponent.props, render(h) { // 用h函数渲染函数式组件,传入实际props数据 return h(MyFunctionalComponent, { props: this.$props }) } }) // 动态修改props的话,直接操作vm的props即可 vm.$props.someProp = 'updated value'
如果是Vue3,写法更轻量化:
import { createApp, h } from 'vue' import MyFunctionalComponent from './MyFunctionalComponent.vue' const app = createApp({ props: MyFunctionalComponent.props, render() { return h(MyFunctionalComponent, { props: this.$props }) } }) app.mount('#target-container')
二、为什么this.$props能生效,直接用FunctionalComponent.props不行?
你混淆了两个完全不同的概念:
FunctionalComponent.props是组件的props配置规则,它只是定义这个组件接受哪些props、每个props的类型/默认值等约束,是一个“规则说明书”,比如:
这里面没有实际的props: { title: { type: String, required: true }, count: { type: Number, default: 0 } }title或count值,只是声明规则,传给函数式组件根本起不到传递数据的作用。this.$props是当前Vue实例(也就是你用来包裹函数式组件的那个实例)的实际props数据集合,里面是带有具体值的键值对,比如{ title: 'Hello', count: 5 },这才是函数式组件需要的实际参数。
简单说:组件的props选项是规则,this.$props是符合规则的实际数据,函数式组件要的是数据,不是规则。
内容的提问来源于stack exchange,提问作者dontboaboutprograming
相关产品推荐
相关产品推荐

