- 函数式组件与普通组件的区别
函数式组件与普通组件的区别
1.函数式组件需要在声明组件是指定 functional
2.不需要实例化,所以没有this,this通过render函数的第二个参数来代替
3.没有生命周期钩子函数,不能使用计算属性,watch
4.不能通过$emit 对外暴露事件,调用事件只能通过context.listeners.click的方式调用外部传入的事件
5.因为函数式组件是没有实例化的,所以在外部通过ref去引用组件时,实际引用的是HTMLElement - 函数式组件优点
1.由于函数式组件不需要实例化,无状态,没有生命周期,所以渲染性能要好于普通组件
2.函数式组件结构比较简单,代码结构更清晰
Vue.component('heading', {
functional: true,
props: ['level', 'title', 'icon'],
render(h, context) {
let children = [];
const {icon, title, level} = context.props
if (icon) {
children.push(h(
'svg',
{ class: 'icon' },
[h('use', { attrs: { 'xlink:href': '#icon-' + icon } })]))
children = children.concat(context.children)
}
vnode = h(
'h' + level,
{ attrs: { title } },
children
)
console.log(vnode);
return vnode
}
})