Vue3 Composition API实战:构建高性能计数器组件
一、Composition API设计哲学
Vue3的Composition API通过逻辑关注点组织代码,解决了Options API在复杂组件中的代码碎片化问题。其核心特性包括:
- reactivity API:ref/reactive实现响应式数据
- 生命周期钩子:onMounted等函数式调用
- 代码复用:通过自定义hook组合逻辑
二、实战案例:智能计数器
下面实现一个具有本地存储持久化、操作历史记录和性能优化的计数器:
// useCounter.js
import { ref, computed, onMounted } from 'vue'
export default function useCounter() {
const count = ref(0)
const history = ref([])
// 初始化从localStorage读取
onMounted(() => {
const saved = localStorage.getItem('counter')
if (saved) count.value = JSON.parse(saved)
})
// 计算方法
const double = computed(() => count.value * 2)
// 操作方法
const increment = () => {
count.value++
history.value.push(`+1 at ${new Date().toLocaleTimeString()}`)
persistCount()
}
const persistCount = () => {
localStorage.setItem('counter', JSON.stringify(count.value))
}
return { count, double, increment, history }
}
组件使用示例:
<!-- CounterComponent.vue -->
<template>
<div>
<p>当前值: {{ count }} (双倍: {{ double }})</p>
<button @click="increment">增加</button>
<ul>
<li v-for="(item, index) in history" :key="index">{{ item }}</li>
</ul>
</div>
</template>
<script setup>
import useCounter from './useCounter'
const { count, double, increment, history } = useCounter()
</script>
三、性能优化技巧
1. 响应式优化:对于不需要响应式的数据,使用shallowRef或markRaw
2. 计算属性缓存:使用computed避免重复计算
3. 防抖处理:对高频操作添加防抖逻辑
import { debounce } from 'lodash-es'
const persistCount = debounce(() => {
localStorage.setItem('counter', JSON.stringify(count.value))
}, 500)
四、扩展思考
本案例可以进一步扩展为:
- 添加服务端同步功能
- 实现撤销/重做功能栈
- 开发多实例状态共享
Composition API使得这些功能的扩展可以保持代码的整洁性和可维护性。