TransferMixin.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. import { mapGetters } from 'vuex'
  2. export default {
  3. /* 提供页面间存在数据传递需要的通用规范 */
  4. data() {
  5. return {
  6. prevData: {}
  7. }
  8. },
  9. computed: {
  10. ...mapGetters(['currentUser'])
  11. },
  12. created() {
  13. const cacheKey = this.$route.query.cacheKey || ''
  14. const data = cacheKey ? localStorage.getItem(cacheKey) : this.$route.query.data
  15. this.prevData = JSON.parse(decodeURIComponent(data || '{}'))
  16. },
  17. methods: {
  18. // transferUrl方法是给上一个页面用的
  19. // config是下一个页面需要的数据格式
  20. // extra是额外的参数提供源,可以是数组,如果当前页面存在prevData,方法会自动引入,不用2次传入
  21. transferData(config, extra) {
  22. if (!config) return {}
  23. let source = {
  24. ...this.prevData
  25. }
  26. if (extra) {
  27. if (Array.isArray(extra)) {
  28. // eslint-disable-next-line no-return-assign
  29. extra.forEach(single => source = {
  30. ...source,
  31. ...single
  32. })
  33. } else {
  34. source = {
  35. ...source,
  36. ...extra
  37. }
  38. }
  39. }
  40. // pick
  41. const nextData = {}
  42. const nextKeys = Array.isArray(config) ? config : Object.keys(config)
  43. // eslint-disable-next-line no-return-assign
  44. nextKeys.forEach(key => nextData[key] = source[key])
  45. return nextData
  46. },
  47. transferTo: function(path, config = null, extra = null, useReplace = false, cacheKey = '') {
  48. if (typeof config === 'boolean') useReplace = config
  49. if (typeof extra === 'boolean') useReplace = extra
  50. if (!extra && typeof config === 'object') extra = config
  51. const nextData = this.transferData(config, extra)
  52. console.log('transfer next data:', nextData)
  53. // 以此解决query会将所有参数转化为string的问题
  54. let query = { data: encodeURIComponent(JSON.stringify(nextData)) }
  55. if (cacheKey) {
  56. const safeKey = this.generateSafeKey(cacheKey)
  57. localStorage.setItem(safeKey, query.data)
  58. query = { cacheKey: safeKey, ts: new Date().getTime() }
  59. }
  60. const location = {
  61. path: path,
  62. query: query
  63. }
  64. if (useReplace !== '_blank') {
  65. return useReplace ? this.$router.replace(location) : this.$router.push(location)
  66. } else {
  67. window.open(this.$router.resolve(location).href, '_blank')
  68. }
  69. },
  70. generateSafeKey(key) {
  71. return `${key}_${this.currentUser.userName}`
  72. }
  73. }
  74. }