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 = this.isEmptyObject(nextData) ? null : { 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 = typeof path === 'string' ? { path: path, query: query } : query ? { ...path, query: query } : path console.log('transfer merged location:', location) 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}` }, isEmptyObject(obj) { if (!obj) return true return Object.keys(obj).length === 0 } } }