IT이야기

Vue.js - Vuex: 모듈스토어를 도우미 파일로 Import할 때 액션이 디스패치되는 이유는 무엇입니까?

cyworld 2022. 5. 29. 09:22
반응형

Vue.js - Vuex: 모듈스토어를 도우미 파일로 Import할 때 액션이 디스패치되는 이유는 무엇입니까?

저는 Vue에서 앱을 만들었습니다.각 모듈은 루트에 대응하며 최상위 컴포넌트(및 다수의 서브 컴포넌트/자녀)를 가진 여러 개의 개별 모듈로 구성됩니다.각 모듈에는 필요한 데이터를 가져오기 위해 컴포넌트의 created() 훅에 디스패치되는 API 콜뿐만 아니라 자체 스토어, 액션, 돌연변이 및 getter가 있습니다.

내 앱의 구조는 다음과 같습니다.

모듈 구조

후보들.표시하다

created() {
    this.$store.dispatch('$_candidates/getAllCandidates');
  },

/sys/sys/_store/actions.module

import api from '../_api';

const getAllCandidates = (context) => {
  api.fetchAllCandidates
    .then((response) => {
      context.commit('ALL_CANDIDATES_FETCHED', response.data.candidate_list);
    })
    .catch((error) => {
      // eslint-disable-next-line
      console.error(error);
    });
};

/sys/syslogs/_api/index.syslogs

import { fetchData } from '@/helpers';

const allCandidatesEndpoint =
  'https://myapiendpoint.io/candidates/list/all';
const fetchAllCandidates = fetchData(allCandidatesEndpoint, 'get');

export default {
  fetchAllCandidates,
};

App.vue의 before Create() 훅에는 모든 애플리케이션 모듈을 한번에 등록하는 도우미 기능이 있습니다.모듈 스토어를 도우미 파일로 Import하여 등록합니다.도우미 파일은 다음과 같습니다.

helpers.delpers.delpers.delpers.

import axios from 'axios';
import { store } from '@/store/store';

import candidatesStore from './modules/candidates/_store';
import dashboardStore from './modules/dashboard/_store';
import eventsStore from './modules/events/_store';
import loginStore from './modules/login/_store';

function fetchData(endpoint, requestType, requestBody) {
  const apiToken = store.state.apiToken;
  delete axios.defaults.auth;
  return axios.request({
    method: requestType,
    data: requestBody,
    url: endpoint,
    headers: {
      'server-token-id': apiToken,
    },
  })
    .then(response => response)
    .catch(error => error);
}

/* Register all of the Vuex modules we'll need to manage application state */

function registerVuexModules() {
  store.registerModule('$_candidates', candidatesStore);
  store.registerModule('$_dashboard', dashboardStore);
  store.registerModule('$_events', eventsStore);
  store.registerModule('$_login', loginStore);
}

function unregisterVuexModules() {
  store.unregisterModule('$_candidates', candidatesStore);
  store.unregisterModule('$_dashboard', dashboardStore);
  store.unregisterModule('$_events', eventsStore);
  store.unregisterModule('$_login', loginStore);
}

export {
  fetchData,
  registerVuexModules,
  unregisterVuexModules,
};

...그리고 App.vue에 다음과 같이 Import합니다.

beforeCreate() {
  registerVuexModules();
},

단, 각 모듈을 Import하면 (fetchData 함수를 사용하여) API 콜이 트리거되어 401이 반환됩니다.helpers.js의 다양한 부분을 코멘트하여 확인하였습니다.기능 자체라기보다는 수입품이 분명합니다.

helpers.js로의 모듈스토어 Import를 삭제해도 해당 모듈의 최상위 컴포넌트에 대한 API 호출은 시행되지 않습니다.나에게 이상한 점은 다음과 같다.

  1. 이러한 API 콜을 트리거하는 액션은 각 모듈의 최상위 컴포넌트에서만 디스패치되지만 로그인 페이지를 새로고침할 때마다 API 콜이 시도됩니다.이러한 컴포넌트가 생성되기 전에도 마찬가지입니다.

  2. Vue-dev-tools는 디스패치되는 액션에 대응하는 이벤트를 등록하지 않습니다.

  3. 도우미 파일에서 스토어 Import를 모두 삭제해도 API 호출은 발생하지 않습니다.

vue-router에서 Import 포맷을 변경하여 컴포넌트의 로드가 느리도록 시도했습니다.이것이 문제인 것 같습니다.번들 크기는 줄었지만 팬텀 API 호출은 수정되지 않았습니다.이렇게 해서 수입하는 건데...

/syslog/index.syslog

import Vue from 'vue';
import Router from 'vue-router';
import axios from 'axios';

import { store } from '../store/store';

/* Lazy load all of the components required for the routes */

const Login = () => import(/* webpackChunkName: "login" */
  '@/modules/login/Login');

const Dashboard = () => import(/* webpackChunkName: "dashboard" */
  '@/modules/dashboard/Dashboard');

...

const router = new Router({

  routes: [
    {
      path: '/',
      name: 'root',
      component: Login,
    },
    {
      path: '/login',
      name: 'login',
      component: Login,
    },
    {
      path: '/dashboard',
      name: 'dashboard',
      component: Dashboard,
      beforeEnter: (to, from, next) => {
        guard(to, from, next);
      },
    },
...

누가 이 행동이나 내가 놓친 것에 대해 설명해 줄 수 있나요?

제가 봤을 때 이 대사 있잖아요.

const fetchAllCandidates = fetchData(allCandidatesEndpoint, 'get');

이 말은 네가 매번import, 이 동작하고 있습니다.fetchData기능을 수행하고 결과를 반환합니다.

아마 네가 대신 이걸 하려고 한 거겠지.

const fetchAllCandidates = function ()
{
  return fetchData(allCandidatesEndpoint, 'get');
}

언급URL : https://stackoverflow.com/questions/52442473/vue-js-vuex-why-is-an-action-dispatched-when-i-import-my-module-stores-to-a-h

반응형