vue2 中如何使用函数式组件
函数式组件(functional component)是一个不持有状态 data
、实例 this
和生命周期的组件。
函数式组件没有 data、生命周期和
this
,函数式组件又叫无状态组件(stateless component)。
模板定义:template functional
<template functional>
<div>
<h1>{
{ props.title }}</h1>
</div>
</template>
<script>
export default {
name: 'FunOne',
props: {
title: [String]
}
}
</script>
<style></style>
render 函数定义 – functional: true
export default {
name: 'FunTwo',
functional: true,
props: {
title: [String]
},
render(h, {
props
}) {
return h('div', {
}, [h('h1', {
}, props.title)])
}
}
不能这样定义:
<template>
<div>
<h1>{
{ title }}</h1>
</div>
</template>
<script>
export default {
name: 'FunOne',
// NOTE 不能这样定义
functional: true,
props: {
title: [String]
}
}
</script>
<style></style>
定义一个函数式组件 MyInput,看看如何使用 props、data 以及事件
MyInput.jsx
export default {
name: 'MyInput',
// 声明是一个函数式组件
functional: true,
props: {
value: {
type: [String, Number],
default: ''
}
},
// NOTE 函数式组件没有 this
render(h, context) {
const {
props,
listeners,
data
} = context
return h('input', {
// DOM 属性
domProps: {
value: props.value
},
on: {
input: ({
target
}) => {
data.on['my-change'](Math.random().toString(36))
// listeners 是 data.on 的别名
listeners['my-input'](target.value)
listeners.input(target.value)
}
}
})
}
}
在 render 函数中使用 MyInput
import MyInput from './MyInput'
export default {
name: 'MyInputExample',