[项目篇]vue3+ts 今天来理解一下自定义hooks - 第五天

2,772 阅读3分钟

这是我参与更文挑战的第21天,活动详情查看:更文挑战

vue3 借鉴 react hooks 开发出了 Composition API ,那么也就意味着 Composition API 也能进行自定义封装 hooks ,接下来我们就用 TypeScript 风格封装一个计数器逻辑的

hooks ( useCount ):

首先来看看这个 hooks 怎么使用:

import { ref } from '/@modules/vue'
import  useCount from './useCount'
 
export default {
  name: 'CountDemo',
  props: {
    msg: String
  },
  setup() {
    const { current: count, inc, dec, set, reset } = useCount(2, {
      min: 1,
      max: 15
    })
    const msg = ref('Demo useCount')
 
    return {
      count,
      inc,
      dec,
      set,
      reset,
      msg
    }
  }
}

出来的效果就是:

image.png

贴上 useCount 的源码:


import { ref, Ref, watch } from 'vue'
 
interface Range {
  min?: number,
  max?: number
}
 
interface Result {
  current: Ref<number>,
  inc: (delta?: number) => void,
  dec: (delta?: number) => void,
  set: (value: number) => void,
  reset: () => void
}
 
export default function useCount(initialVal: number, range?: Range): Result {
  const current = ref(initialVal)
  const inc = (delta?: number): void => {
    if (typeof delta === 'number') {
      current.value += delta
    } else {
      current.value += 1
    }
  }
  const dec = (delta?: number): void => {
    if (typeof delta === 'number') {
      current.value -= delta
    } else {
      current.value -= 1
    }
  }
  const set = (value: number): void => {
    current.value = value
  }
  const reset = () => {
    current.value = initialVal
  }
 
  watch(current, (newVal: number, oldVal: number) => {
    if (newVal === oldVal) return
    if (range && range.min && newVal < range.min) {
      current.value = range.min
    } else if (range && range.max && newVal > range.max) {
      current.value = range.max
    }
  })
 
  return {
    current,
    inc,
    dec,
    set,
    reset
  }
}

分析源码

这里首先是对 hooks 函数的入参类型和返回类型进行了定义,入参的 Range 和返回的 Result 分别用一个接口来指定,这样做了以后,最大的好处就是在使用 useCount 函数的时候,ide就会自动提示哪些参数是必填项,各个参数的类型是什么,防止业务逻辑出错。

image.png

接下来,在增加 inc 和减少 dec 的两个函数中增加了 typeo 类型守卫检查,因为传入的 delta 类型值在某些特定场景下不是很确定,比如在 template 中调用方法的话,类型检查可能会失效,传入的类型就是一个原生的 Event 。

搞掂收工,有不懂的尽管问,我有空就会回复的啦

大佬们,感兴趣可以关注我公众号鸭,现在还是个位数呢,委屈屈...

人懒,不想配图,望能帮到大家

公众号:小何成长,佛系更文,都是自己曾经踩过的坑或者是学到的东西

有兴趣的小伙伴欢迎关注我哦,我是:何小玍。 大家一起进步鸭

记叙文:

技术文

乱七八糟系列

vue系列

typescript系列

react-native系列