123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475 |
- import { mapGetters } from 'vuex'
- export default {
- /* 提供页面间存在数据传递需要的通用规范 */
- data() {
- return {
- prevData: {}
- }
- },
- computed: {
- ...mapGetters(['currentUser'])
- },
- created() {
- const cacheKey = this.$route.query.cacheKey || ''
- const data = cacheKey ? localStorage.getItem(cacheKey) : this.$route.query.data
- this.prevData = JSON.parse(decodeURIComponent(data || '{}'))
- },
- methods: {
- // transferUrl方法是给上一个页面用的
- // config是下一个页面需要的数据格式
- // extra是额外的参数提供源,可以是数组,如果当前页面存在prevData,方法会自动引入,不用2次传入
- transferData(config, extra) {
- if (!config) return {}
- let source = {
- ...this.prevData
- }
- if (extra) {
- if (Array.isArray(extra)) {
- // eslint-disable-next-line no-return-assign
- extra.forEach(single => source = {
- ...source,
- ...single
- })
- } else {
- source = {
- ...source,
- ...extra
- }
- }
- }
- // pick
- const nextData = {}
- const nextKeys = Array.isArray(config) ? config : Object.keys(config)
- // eslint-disable-next-line no-return-assign
- nextKeys.forEach(key => nextData[key] = source[key])
- return nextData
- },
- transferTo: function(path, config = null, extra = null, useReplace = false, cacheKey = '') {
- if (typeof config === 'boolean') useReplace = config
- if (typeof extra === 'boolean') useReplace = extra
- if (!extra && typeof config === 'object') extra = config
- const nextData = this.transferData(config, extra)
- console.log('transfer next data:', nextData)
- // 以此解决query会将所有参数转化为string的问题
- let query = { data: encodeURIComponent(JSON.stringify(nextData)) }
- if (cacheKey) {
- const safeKey = this.generateSafeKey(cacheKey)
- localStorage.setItem(safeKey, query.data)
- query = { cacheKey: safeKey, ts: new Date().getTime() }
- }
- const location = {
- path: path,
- query: query
- }
- if (useReplace !== '_blank') {
- return useReplace ? this.$router.replace(location) : this.$router.push(location)
- } else {
- window.open(this.$router.resolve(location).href, '_blank')
- }
- },
- generateSafeKey(key) {
- return `${key}_${this.currentUser.userName}`
- }
- }
- }
|