vue3个人最佳实践记录(1)- 所有api全部封装成hook,摒弃了api按模块功能分的心智负担

313 阅读1分钟

今天起API不在是心智负担

api这块 我感觉其实每个接口都可以封装成一个hook,不用去思考如何应该归类到那个文件中(心智负担),提供公共hook,同时导出api 进可攻 退可守

特别注意的一点导出的hook一定要加上后缀Api遵循命名规范

// useOptionsApi.js
import request from '@/utils/request.js'
import {
  computed,
  ref
} from 'vue'

export const getOptions = () => {
  return request({
    url: '/api/v1/getOptions',
    method: 'get',
  })
}

export const useOptionsApi = () => {
  const options = ref([])

  const setOptions = () => {
    getOptions().then((list) => {
      options.value = list
    })
  }

  const optionMap = computed(() => {
    return options.value.reduce(
      (
        map,
        {
          id,
          name
        }
      ) => {
        map[id] = name
        return map
      },
      {}
    )
  })
  
  // 这里还可以导出常用的数据

  return {
    options,
    setOptions,
    optionMap
  }
}

这块会涉及一些特别的api,比如修改,没有数据上的返回,只是告诉你操作是否成功

// useUpdateUserApi.js
import request from '@/utils/request.js'

export const getOptions = (id) => {
  return request({
    url: `/api/v1/update/user/${id}`,
    method: 'get',
  })
}

2.枚举值可能长时间不会变化可以增加一个缓存,有的同学可能比较在乎api的请求过多的问题,可以增加一个hook 这块useCache的实现就是一个demo,主要是要做到惰性单例去请求api

export const useCache = (factory) => {
  const cache = ref(null)
  const activated = ref(false)

  const execute = (flush = false) => {
    if (!activated.value || flush) {
      activated.value = true
      cache.value = factory()
    }

    return new Promise((resolve, reject) => {
      resolve(cache.value)
    })
  }

  return {
    execute
  }
}

const { execute } = useCache(() => getOutputRiskTypeList())

const setOptions = (flush = false) => {
    execute(flush).then((list) => {
      options.value = list
    })
}

可能很多人不明白为什么要这么做 其实从外观角度去看
假设有A、B两个组件需要用到setOptions(基于缓存实现),从代码实现上使组件完全独立

后续会陆续分享vue3个人觉得最佳实践