programing

BeforeRouteEnter 함수 및 Vuex 문제

yoursource 2022. 12. 1. 23:49
반응형

BeforeRouteEnter 함수 및 Vuex 문제

퀘이사 프로젝트에서 Vuex 함수 "asyncValidate"가 있습니다.토큰"을 사용하여 사용자가 시스템에 로그인하고 있는지 여부를 확인합니다.이 파일은 "src/store/index.js" 파일에 있습니다.파일에는 다음 코드가 포함되어 있습니다.

import Vue from 'vue'
import Vuex from 'vuex'

import { api } from 'boot/axios'

Vue.use(Vuex)

export default function (/* { ssrContext } */) {
  const Store = new Vuex.Store({
    state: {
      isLogin: false
    },
    mutations: {
      changeIsLogin (state, payload) {
          state.isLogin = payload;
      }
    },
    actions: {
      asyncValidateToken: async (context, payload) => {
        await api.post('/accounts/token', '', {
          headers: {
              'Authorization': `Bearer ${localStorage.token}`,
            }
        })
        .then(response => {
          if (response.data == localStorage.userId) {
              context.commit('changeIsLogin', true);
              return true;
          } else {
              context.commit('changeIsLogin', false);
              return false;
          }
        })
        .catch(error => {
          context.commit('changeIsLogin', false);
          return false;
        });
      }
    }
  })

  return Store
}

"beforeRouteEnter" 함수를 통해 경로 보호가 사용되는 "Results.vue" 페이지

<template>
  <q-page class="flex flex-center">
    <div>
      <charts />
      <feedback />
    </div>
  </q-page>
</template>


<script>
import Charts from 'src/components/Charts.vue'
import Feedback from 'src/components/Feedback.vue'
import store from 'src/store/index.js'

export default {
  name: 'Results',
  components: {
    Charts,
    Feedback
  },
  beforeRouteEnter (to, fromR, next) {
    if (store.dispatch('asyncValidateToken')) { 
      next();
    } else { this.$router.push('/login'); }
  }
}
</script>

에러 「src_store_index_js_」가 표시됩니다.WEBPACK_IPORTED_MODULE_2_.default.dispatch는 RouteEnter 이전 함수가 아닙니다(Results.vue).routeEnterGuard(vue-router.esm.js?85f8:2333)에 있습니다.건설은 "이것"입니다.$store.dispatch('asyncValidate')토큰''도 작동하지 않습니다. 왜일까요?

해라

store().dispatch('')

왜요?

왜냐하면 당신의store.jsmodule은 함수를 기본값으로 내보내고 있으며 스토어를 반환합니다.

언급URL : https://stackoverflow.com/questions/66900867/beforerouteenter-function-and-vuex-problem

반응형