主题
渲染原理
渲染函数
提示
js
Vue.component('anchored-heading', {
render: function (createElement) {
return createElement(
'h' + this.level, // 标签名称
this.$slots.default, // 子节点数组
)
},
props: {
level: {
type: Number,
required: true,
},
},
})
JSX
https://v2.cn.vuejs.org/v2/guide/render-function.html#JSX
函数式组件
https://v2.cn.vuejs.org/v2/guide/render-function.html#函数式组件
js
Vue.component('my-component', {
functional: true,
// Props 是可选的
props: {
// ...
},
// 为了弥补缺少的实例
// 提供第二个参数作为上下文
render: function (createElement, context) {
// ...
},
})
提示
注意:
- 在
2.3.0
之前 的版本中,如果一个函数式组件想要接收 prop,则props
选项是必须的。 - 在
2.3.0
或以上 的版本中,可以省略 props 选项,所有组件上的attribute
都会被自动隐式解析为prop
。
当使用函数式组件时,该引用将会是 HTMLElement
,因为他们是无状态的也是无实例的。
在 2.5.0
及以上版本中,如果使用了单文件组件,那么基于模板的函数式组件可以这样声明:
template
<template functional>
</template>