用 Vue 时,常出现相关业务逻辑代码散在 data, methods, watch, computed 和 mounted 等地方。这样的代码可维护性差。查找或更改这块逻辑时,都要找多个地方。
解决方案
Vue 3 新出的 Composition API 可以优雅的聚集零散业务代码。 Composition API 通过 ref,reactive,watch,computed, onMounted 等这些可调用的函数,来聚集代码。
我们来看个 Demo。实现一个计数器,支持按加,减按钮来改数字,改数字时,要将新的值传给服务器端。
常规写法:
<template><div><button @click="decrease"> -1 </button>{{count}}<button @click="increase"> +1 </button></div></template><script>export default {data() {return {count: 1}},watch: {count(newValue) {this.report(newValue)}},methods: {increase() {this.count++},decrease() {this.count--},report(count) {console.log(`report num: ${count}`)}}}</script>
业务逻辑代码散在 data,watch 和 methods 里。
用 Composition API 写,可以将业务代码聚集在一处。Composition API 和 常规写法的 DOM 结构没有变化,只有 js 有变化。如下:
<script setup>import {ref, watch} from 'vue'const count = ref(1)const setCount = (value) => {count.value = value}const increase = () => setCount(count.value + 1)const decrease = () => setCount(count.value - 1)const report = count => console.log(`report num: ${count}`)watch(count, newValue => report(newValue))</script>
为了方便计数器逻辑的复用,可以抽象成一个函数:
import {ref, watch} from 'vue'export default function useCount(initValue = 1, onChange) {const count = ref(initValue)const setCount = (value) => {count.value = value}watch(count, newValue => onChange(newValue))const increase = () => setCount(count.value + 1)const decrease = () => setCount(count.value - 1)return {count,increase,decrease}
使用:
<script setup>import useCount from './use-count'const report = count => console.log(`report num: ${count}`)const {count, increase, decrease} = useCount(1, report)</script>
代码是不是变得很内聚,用 Composition API 来重构零散的代码吧~
