useVoluntaryDataInjection.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. import {ref, watch} from 'vue';
  2. import {injectLocal, provideLocal, toValue} from "@vueuse/core";
  3. import {useUserStore} from "@/hooks/useUserStore";
  4. import {useCacheStore} from "@/hooks/useCacheStore";
  5. import {cacheActions} from "@/hooks/defineCacheActions";
  6. import {toast} from "@/uni_modules/uv-ui-tools/libs/function";
  7. import {empty} from "@/uni_modules/uv-ui-tools/libs/function/test";
  8. const key = Symbol('VOLUNTARY_DATA')
  9. /*本来voluntary data在批次/计划/专业线都是通用的,理论上它应该是全局性的
  10. * 但由于它和年份和当前用户相关,如果造成全局,year参数的影响性对开发者容易乎略
  11. * 所以这里定义为依赖注入,缩小影响范围*/
  12. export const useProvideVoluntaryData = function (yearRef) {
  13. const {currentUser, isLogin} = useUserStore()
  14. const {dispatchCache} = useCacheStore()
  15. const voluntaryData = ref({})
  16. const loadData = async () => {
  17. let payload = undefined
  18. if (yearRef) {
  19. const year = toValue(yearRef)
  20. if (!year) return
  21. payload = {year}
  22. }
  23. voluntaryData.value = await dispatchCache(cacheActions.getVoluntaryData, payload)
  24. }
  25. const validate = async (score, silence) => {
  26. if (empty(voluntaryData.value)) {
  27. return Promise.reject('VoluntaryData not be loaded.')
  28. }
  29. if (!score) {
  30. if (!silence) toast('请输入分数')
  31. return Promise.reject(false)
  32. }
  33. if (!/^[1-9]\d*$/.test(score)) {
  34. if (!silence) toast('分数必须为正整数')
  35. return Promise.reject(false)
  36. }
  37. if (score > voluntaryData.value.maxScore) {
  38. if (!silence) toast(`分数不能超过${voluntaryData.value.maxScore}`)
  39. return Promise.reject(false)
  40. }
  41. return true
  42. }
  43. const dependents = yearRef ? [currentUser, yearRef] : [currentUser]
  44. watch(dependents, () => isLogin.value && loadData(), {immediate: true})
  45. const options = {
  46. voluntaryData,
  47. validate
  48. }
  49. provideLocal(key, options)
  50. return options
  51. }
  52. export const useInjectVoluntaryData = function () {
  53. return injectLocal(key)
  54. }