visited.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. import { mapState } from 'vuex'
  2. import VisitedModelTransform from '@/utils/mixins/tran-visited'
  3. class VisitedPathItem {
  4. constructor (path, search) {
  5. this.path = path
  6. this.search = search
  7. this.timestamp = Date.now()
  8. }
  9. }
  10. const TranModel = new VisitedModelTransform()
  11. export const mixinVisited = {
  12. computed: {
  13. ...mapState({
  14. visitedList: state => state.user.visitedList
  15. })
  16. },
  17. created () {
  18. this.$store.commit('user/refreshVisited')
  19. },
  20. methods: {
  21. createPathItem (path, search) {
  22. return TranModel.transformItem(new VisitedPathItem(path, search))
  23. },
  24. // 从判断 path 是否访问过
  25. // 参数path为 VisitedPathItem new 出来的实例
  26. pathVisitedIndex (path) {
  27. const list = this.visitedList
  28. let sameIndex = -1
  29. if (list) {
  30. for (let i = 0; i < list.length; i++) {
  31. const same = this.comparePath(list[i], path)
  32. if (same) {
  33. sameIndex = i
  34. break
  35. }
  36. }
  37. }
  38. return sameIndex
  39. },
  40. comparePath (basePath, newPath) {
  41. const pathSame = basePath.type === newPath.type
  42. const searchSame = basePath.id === newPath.id
  43. return pathSame && searchSame
  44. },
  45. pathVisited (path) {
  46. return this.pathVisitedIndex(path) !== -1
  47. },
  48. // 保存一条历史
  49. // 参数path为 VisitedPathItem new出来的实例
  50. pathVisiting (path) {
  51. if (!path) return
  52. // 判断是否重复
  53. const index = this.pathVisitedIndex(path)
  54. const visitedList = JSON.parse(JSON.stringify(this.visitedList))
  55. if (index >= 0) {
  56. // 已存在
  57. const itemArr = visitedList.splice(index, 1)
  58. const item = itemArr[0]
  59. item.timestamp = Date.now()
  60. visitedList.unshift(item)
  61. } else {
  62. visitedList.unshift(path)
  63. }
  64. // 全量替换
  65. this.$store.commit('user/addVisited', visitedList)
  66. }
  67. }
  68. }