函数式组件
1.特点
- 没有this(没有实例)
- 没有响应式数据
- 它只是一个接受一些 prop 的函数。
Vue.component('my-component', {
functional: true,
// Props 是可选的
props: {
// ...
},
// 为了弥补缺少的实例
// 提供第二个参数作为上下文
render: function (createElement, context) {
// ...
}
})
// 在 2.5.0 及以上版本中,如果你使用了单文件组件,那么基于模板的函数式组件可以这样声明:
<template functional>
...
</template>
2.应用场景:
- 1.程序化的在多个组件中选择一个来代为渲染;
- 2.在将children,props,data传递给子组件之前操作它们
var EmptyList = { /* ... */ }
var TableList = { /* ... */ }
var OrderedList = { /* ... */ }
var UnorderedList = { /* ... */ }
Vue.component('smart-list', {
functional: true,
props: {
items: {
type: Array,
required: true
},
isOrdered: Boolean
},
render: function (createElement, context) {
function appropriateListComponent () {
var items = context.props.items
if (items.length === 0) return EmptyList
if (typeof items[0] === 'object') return TableList
if (context.props.isOrdered) return OrderedList
return UnorderedList
}
return createElement(
appropriateListComponent(),
context.data,
context.children
)
}
})
知识点:渲染函数,createElement,context
- 1.vue一般使用模板创建html,但是在一些场景中,需要用JavaScript的完全编程能力,就使用渲染函数render,它比模板更接近编译器,渲染开销低很多,性能好。
- 2.createElement (
/* 三个参数*/
// {String | Object | Function}
// 一个 HTML 标签名、组件选项对象,或者
// resolve 了上述任何一种的一个 async 函数。必填项。
‘div’,
// {Object}
// 一个与模板中属性对应的数据对象。可选。
{
props:{
data:{}
}
},
// {String | Array}
// 子级虚拟节点 (VNodes),由 createElement()
构建而成,
// 也可以使用字符串来生成“文本虚拟节点”。可选。
[
‘先写一些文字’,
createElement(‘h1’, ‘一则头条’),
createElement(MyComponent, {
props: {
someProp: ‘foobar’
}
})
]
)
- 3.组件需要的一切都是通过 context 参数传递,它是一个包括如下字段的对象:
- props:提供所有 prop 的对象
- children:VNode 子节点的数组
- slots:一个函数,返回了包含所有插槽的对象
- scopedSlots:(2.6.0+) 一个暴露传入的作用域插槽的对象。也以函数形式暴露普通插槽。
- data:传递给组件的整个数据对象,作为 createElement 的第二个参数传入组件
- parent:对父组件的引用
- listeners:(2.3.0+) 一个包含了所有父组件为当前组件注册的事件监听器的对象。这是 data.on 的一个别名。
- injections:(2.3.0+) 如果使用了 inject 选项,则该对象包含了应当被注入的属性。
因为函数式组件只是函数,所以渲染开销也低很多。
Vue.component('anchored-heading', {
functional:true,
render: function (createElement,context) {
return createElement(
'h' + context.props.level, // 标签名称
context.children // 子节点数组
)
},
props: {
level: {
type: Number,
required: true
}
}
})
如果你使用基于模板的函数式组件,那么你还需要手动添加 attribute 和监听器。因为我们可以访问到其独立的上下文内容,所以我们可以使用 data.attrs 传递任何 HTML attribute,也可以使用 listeners (即 data.on 的别名) 传递任何事件监听器。
<template functional>
<button
class="btn btn-primary"
v-bind="data.attrs"
v-on="listeners"
>
<slot/>
</button>
</template>
还有更多可以参考vue文档