IT이야기

(vue 구성 요소 대신) Javascript 파일에서 작업을 디스패치하는 방법?

cyworld 2022. 3. 22. 21:38
반응형

(vue 구성 요소 대신) Javascript 파일에서 작업을 디스패치하는 방법?

나는 vue 컨텍스트 밖에 하나의 모듈(javascript 파일)이 있다.이 자바스크립트 파일에서 액션을 보내야 해그것이 가능한가? 만약 그렇다면, 어떻게?

jsfile.js(Javascript 파일)

const detail = {};

detail.validateLocation = (location) => {
  // need to dispatch one action from here.
  // dispatch('SET_LOCATION', {city: 'California'})
  // how to dispatch action ?
}

export default detail;

action.js

export default {
  SET_LOCATION: ({ commit}, data) => {
    commit('SET_LOCATION', data);
  },
}

store.js.

import Vue from 'vue';
import Vuex from 'vuex';
import actions from './actions';
import mutations from './mutations';
import getters from './getters';
export function createStore() {
  return new Vuex.Store({
    modules: {},
    state: {
      location: null
    },
    actions,
    mutations,
    getters,
  });
}

먼저 store.js에 스토어를 생성하십시오.

import Vue from 'vue';
import Vuex from 'vuex';
import actions from './actions';
import mutations from './mutations';
import getters from './getters';

const store = new Vuex.Store({
    modules: {},
    state: {
      location: null
    },
    actions,
    mutations,
    getters,
  });

export default store

그런 다음 저장소를 jsfile.js로 가져와 사용한다.

import store from "./store"

const detail = {};

detail.validateLocation = (location) => {
  // Use imported store
  store.dispatch('SET_LOCATION', {city: 'California'})
}

export default detail;

Vue 인스턴스를 생성하는 기본 또는 인덱스 파일이 있다고 가정할 경우 이제 가져오기 기능을 생성 기능 가져오기에서 스토어 가져오기만으로 변경해야 할 수 있다.

참조URL: https://stackoverflow.com/questions/46716709/how-to-dispatch-action-from-a-javascript-file-instead-of-a-vue-component

반응형