猫妈狗爸伴宠师小程序前端代码
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

97 lines
2.6 KiB

  1. // 答题数据本地存储工具
  2. const EXAM_STORAGE_KEY = 'exam_answers_data'
  3. const examStorage = {
  4. // 保存答题数据
  5. saveAnswer: function(examType, questionId, value) {
  6. try {
  7. let examData = uni.getStorageSync(EXAM_STORAGE_KEY) || {}
  8. // 确保examType存在
  9. if (!examData[examType]) {
  10. examData[examType] = {}
  11. }
  12. // 保存答案
  13. examData[examType][questionId] = {
  14. value: value,
  15. timestamp: Date.now()
  16. }
  17. uni.setStorageSync(EXAM_STORAGE_KEY, examData)
  18. } catch (error) {
  19. console.error('保存答题数据失败:', error)
  20. }
  21. },
  22. // 获取答题数据
  23. getAnswer: function(examType, questionId) {
  24. try {
  25. let examData = uni.getStorageSync(EXAM_STORAGE_KEY) || {}
  26. if (examData[examType] && examData[examType][questionId]) {
  27. return examData[examType][questionId].value
  28. }
  29. return null
  30. } catch (error) {
  31. console.error('获取答题数据失败:', error)
  32. return null
  33. }
  34. },
  35. // 获取某个考试类型的所有答题数据
  36. getAllAnswers: function(examType) {
  37. try {
  38. let examData = uni.getStorageSync(EXAM_STORAGE_KEY) || {}
  39. return examData[examType] || {}
  40. } catch (error) {
  41. console.error('获取所有答题数据失败:', error)
  42. return {}
  43. }
  44. },
  45. // 清除某个考试类型的答题数据
  46. clearExamAnswers: function(examType) {
  47. try {
  48. let examData = uni.getStorageSync(EXAM_STORAGE_KEY) || {}
  49. if (examData[examType]) {
  50. delete examData[examType]
  51. uni.setStorageSync(EXAM_STORAGE_KEY, examData)
  52. }
  53. } catch (error) {
  54. console.error('清除答题数据失败:', error)
  55. }
  56. },
  57. // 清除所有答题数据
  58. clearAllAnswers: function() {
  59. try {
  60. uni.removeStorageSync(EXAM_STORAGE_KEY)
  61. } catch (error) {
  62. console.error('清除所有答题数据失败:', error)
  63. }
  64. },
  65. // 检查答题数据是否过期(可选功能,比如24小时后过期)
  66. isAnswerExpired: function(examType, questionId, expireHours = 24) {
  67. try {
  68. let examData = uni.getStorageSync(EXAM_STORAGE_KEY) || {}
  69. if (examData[examType] && examData[examType][questionId]) {
  70. const timestamp = examData[examType][questionId].timestamp
  71. const now = Date.now()
  72. const expireTime = expireHours * 60 * 60 * 1000 // 转换为毫秒
  73. return (now - timestamp) > expireTime
  74. }
  75. return true // 没有数据视为过期
  76. } catch (error) {
  77. console.error('检查答题数据过期失败:', error)
  78. return true
  79. }
  80. }
  81. }
  82. export default examStorage