TransferMixin.js 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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 = this.isEmptyObject(nextData) ? null : { 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 = typeof path === 'string' ? {
  61. path: path,
  62. query: query
  63. } : query ? {
  64. ...path,
  65. query: query
  66. } : path
  67. console.log('transfer merged location:', location)
  68. if (useReplace !== '_blank') {
  69. return useReplace ? this.$router.replace(location) : this.$router.push(location)
  70. } else {
  71. window.open(this.$router.resolve(location).href, '_blank')
  72. }
  73. },
  74. generateSafeKey(key) {
  75. return `${key}_${this.currentUser.userName}`
  76. },
  77. isEmptyObject(obj) {
  78. if (!obj) return true
  79. return Object.keys(obj).length === 0
  80. }
  81. }
  82. }