// other special top-level properties
class={{ foo: true, bar: false }}
style={{ color: 'red', fontSize: '14px' }}
key="key"
ref="ref"
// assign the `ref` is used on elements/components with v-for
refInFor
slot="slot">
</div>
)
}
上面有个地方需要注意,当给自定义组件绑定事件时用nativeOnClick,而模板格式是用
@click.native,另外当用到给函数式组件绑定事件时就有点小坑了下面说。
JSX中的函数式组件
函数式组件无状态,无this实例,下面是vue文档中提到的一段话:
因为函数式组件只是一个函数,所以渲染开销也低很多。然而,对持久化实例的缺乏也意味着函数式组件不会出现在 Vue devtools 的组件树里。
我个人理解因为没了状态(data),少了很多响应式的处理,还有生命周期等过程会提高速度和减少内存占用吧?
函数式组件也可以在模板格式中用只需要这样
<template functional></template>
那jsx中的函数式组件呢?也很简单只需增加配置functional: true就可以了
那函数式组件没有了this 实例怎么绑定事件怎么获取props呢?
组件需要的一切都是通过上下文传递,包括:
props : 提供所有 prop 的对象
children: VNode 子节点的数组
slots: 返回所有插槽的对象的函数
data:传递给组件的数据对象,并将这个组件作为第二个参数传入 createElement
上面我只列举了部分属性,这些是非函数式组件的东西,对于函数式组件
vue 增加了context对象,需要作为render(h,context) 第二个参数传入,this.$slots.default更新为context.children props原本是直接挂在this上的,现在变为context.props挂在了context.props上。this.data变为了context.data
需要注意的是对于函数式组件,没有被定义为prop的特性不会自动添加到组件的根元素上,意思就是需要我们手动添加到组件根元素了,看个例子吧
//父组件
...省略无关代码
render(){
return (
<Item data={this.data} class="large"/>
)
}
//Item.vue组件
export default {
functional:true,
name: "item",
render(h,context){
return (
<div class="red" >
{context.props.data}
</div>
)
}
}
上面代码期待的是.large类名传入到了Item的根元素上,但是其实没有。我们需要增加点东西
// Item.vue
export default {
functional:true,
name: "item",
render(h,context){
return (
<div class="red" {...context.data}>










