Vue函数实现
Vue 函数式组件实现
函数式组件在 Vue 中是一种无状态(无 data)和无实例(无 this 上下文)的组件形式,通常用于性能优化或简单渲染逻辑。
定义函数式组件

// 方式1:通过 functional 选项
export default {
functional: true,
render(h, context) {
return h('div', context.props.text)
}
}
使用 setup 函数(Vue 3)

import { h } from 'vue'
export default {
setup(props) {
return () => h('div', props.text)
}
}
高阶函数封装
利用工厂函数生成可复用的逻辑:
function withLoading(WrappedComponent) {
return {
data() {
return { isLoading: false }
},
methods: {
showLoading() { this.isLoading = true },
hideLoading() { this.isLoading = false }
},
render(h) {
return h(WrappedComponent, {
props: {
...this.$props,
loading: this.isLoading
}
})
}
}
}
组合式函数(Vue 3)
使用 composables 实现逻辑复用:
// useCounter.js
import { ref } from 'vue'
export function useCounter(initialValue = 0) {
const count = ref(initialValue)
const increment = () => count.value++
return { count, increment }
}
// 组件中使用
import { useCounter } from './useCounter'
export default {
setup() {
const { count, increment } = useCounter()
return { count, increment }
}
}
渲染函数注意事项
- 使用
h()函数创建虚拟节点 - 事件监听需通过
on前缀指定,如onClick - 插槽内容通过
context.slots()访问
render(h) {
return h('button', {
on: {
click: this.handleClick
}
}, this.$slots.default)
}






