探索Vue高阶组件的使用

2020-06-16 06:24:45易采站长站整理
钩子,打印
I have already mounted

以上就完成了与

mixins
同样的功能,不过这一次我们采用的是高阶组件,所以是非侵入式的,我们没有修改原组件(
WrappedComponent
),而是在新组件中渲染了原组件,并且没有对原组件做任何修改。并且这里大家要注意
$listeners
$attrs


'<wrapped v-on="$listeners" v-bind="$attrs"/>'

这么做是必须的,这就等价于在

React
中透传
props


<WrappedComponent {...this.props}/>

否则在使用高阶组件的时候,被包装组件(

WrappedComponent
)接收不到
props
事件

那这样真的就完美解决问题了吗?不是的,首先

template
选项只有在完整版的
Vue
中可以使用,在运行时版本中是不能使用的,所以最起码我们应该使用渲染函数(
render
)替代模板(
template
),如下:

hoc.js


export default function WithConsole (WrappedComponent) {
return {
mounted () {
console.log('I have already mounted')
},
render (h) {
return h(WrappedComponent, {
on: this.$listeners,
attrs: this.$attrs,
})
}
}
}

上面的代码中,我们将模板改写成了渲染函数,看上去没什么问题,实则不然,上面的代码中

WrappedComponent
组件依然收不到
props
,有的同学可能会问了,我们不是已经在
h
函数的第二个参数中将
attrs
传递过去了吗,怎么还收不到?当然收不到,
attrs
指的是那些没有被声明为
props
的属性,所以在渲染函数中还需要添加
props
参数:

hoc.js


export default function WithConsole (WrappedComponent) {
return {
mounted () {
console.log('I have already mounted')
},
render (h) {
return h(WrappedComponent, {