vue 高阶组件;高阶组件
1. 什么是高阶组件
高阶组件是一个函数,传给它一个组件,它返回一个新的组件。
2. 高阶组件的作用
高阶组件的作用是用于组件之间代码的复用,它不会修改原组件,只是通过包裹的方式来增强组件的功能。比如:表单验证、表单提交、表单重置、表单数据回显等等。
3. 高阶组件的使用
// 高阶组件
function withComponent (Component) {
return {
render (h) {
return h(Component)
}
}
}
// 普通组件
const Component = {
render (h) {
return h('div', '我是普通组件')
}
}
// 使用高阶组件包裹普通组件
const NewComponent = withComponent(Component)
例子1:创建一个简单的高阶组件
这里有一个例子,用于展示高阶组件的使用。你可以使用你擅长的框架来实现这个例子。比如:Vue、React、Angular等等。
这里以Vue为例。
让我们使用刚才的高阶组件来实现一个功能:点击按钮,弹出提示框。
<template>
<div>
<h1>高阶组件</h1>
<NewButton></NewButton>
</div>
</template>
<script>
import { h } from 'vue'
// 高阶组件
function withAlert(Component) {
return {
render() {
return h(Component, {
onClick: () => {
alert('点击了按钮')
}
})
}
}
}
// 普通组件
const Button = {
render() {
return h('button','hello world');
}
}
// 使用高阶组件包裹普通组件
const NewButton = withAlert(Button)
export default {
components: {
NewButton
}
}
</script>
清注意,在vue2中,你可能需要使用:
on:{ click:()=>{ alert('点击了按钮') } }
来代替:
onClick:()=>{ alert('点击了按钮') }
例子2:使用element-ui的高阶组件
这里使用一个常用的UI框架element-ui来实现一个例子,让我们来看看element-ui是如何使用高阶组件的。
<template>
<div style="margin: 50px;">
<h1>高阶组件</h1>
<NewButton></NewButton>
</div>
</template>
<script>
import { ElInput } from 'element-plus';
// 高阶组件
const NewButton = {
components: {
ElInput
},
data() {
return {
value: ''
}
},
render() {
return (
<ElInput v-model={this.value} />
)
}
}
export default {
components: {
NewButton
}
}
</script>
你可能已经注意到,这里我们没有使用h函数,而是使用了jsx语法。如果是初学者,你可能会感觉到有些困惑。你可以去多了解一下jsx语法,高阶组件的使用不仅仅局限于h函数。