App.vue 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. <template>
  2. <router-view v-if="ready" />
  3. </template>
  4. <script>
  5. import { mapMutations, mapActions } from 'vuex'
  6. export default {
  7. data () {
  8. return {
  9. ready: false,
  10. }
  11. },
  12. methods: {
  13. ...mapMutations('user', {
  14. updateUser: 'UPDATE_USER',
  15. }),
  16. ...mapActions('user', {
  17. refreshUser: 'refresh',
  18. }),
  19. async checkUser () {
  20. // 作为子站点打开
  21. if (this.isMinion) return this.pushMessage('sign')
  22. // 独立打开
  23. const token = window.localStorage.getItem('token')
  24. const ttl = window.localStorage.getItem('token_ttl')
  25. if (token && ttl && new Date() < new Date(Number(ttl))) {
  26. try {
  27. await this.refreshUser()
  28. } catch {
  29. this.goSign()
  30. }
  31. } else this.goSign()
  32. },
  33. goSign () {
  34. this.$router.replace({ name: 'sign' })
  35. },
  36. pushMessage (type, payload = {}) {
  37. const { SYSTEM_NAME, MAIN_URL } = process.env
  38. window.parent.postMessage({
  39. system: SYSTEM_NAME,
  40. type,
  41. payload,
  42. }, MAIN_URL)
  43. },
  44. receiveMessage ({ data: { type, payload }, origin }) {
  45. if (origin === window.origin) return
  46. const messageTypes = {
  47. sign: () => {
  48. this.updateUser(payload)
  49. this.ready = true
  50. this.pushMessage('ready')
  51. },
  52. view: () => {
  53. this.$router.push({ path: `/${payload.view}/` })
  54. },
  55. }
  56. if (messageTypes[type]) messageTypes[type]()
  57. },
  58. },
  59. mounted () {
  60. window.UPLOAD_URL = process.env.API_URL.upload ||
  61. `${process.env.API_URL.default}config/upload`
  62. const handleError = (content, cb) => {
  63. this.$Message.error({ content })
  64. if (cb) cb()
  65. }
  66. this.isMinion = this.$store.state.isMinion
  67. this.ready = !this.isMinion
  68. this.$hub.$on('GLOBAL_AUTH_ERROR', ({ message }) => {
  69. handleError(message, () => {
  70. if (this.isMinion) return this.pushMessage('sign', { resign: true })
  71. this.$router.replace({ name: 'sign' })
  72. })
  73. })
  74. this.$hub.$on('GLOBAL_ERROR', ({ message }) => {
  75. handleError(message)
  76. })
  77. window.addEventListener('message', this.receiveMessage, false)
  78. this.checkUser()
  79. },
  80. }
  81. </script>