【问题标题】:How to dispatch action from a javascript file (instead of a vue component)?如何从 javascript 文件(而不是 vue 组件)调度操作?
【发布时间】:2018-03-24 19:27:04
【问题描述】:

我在 vue 上下文之外有一个模块(javascript 文件)。我需要从这个 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,
  });
}

【问题讨论】:

    标签: vue.js vuejs2 vuex


    【解决方案1】:

    首先,在 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
    

    然后,将 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 实例的主文件或索引文件,您现在可能需要将导入从导入 create 函数更改为仅导入 store。

    【讨论】:

    • 我的做法是: import { createStore } from '../store';常量存储 = createStore(); store.dispatch('SET_LOCATION', {city: 'California'});但它不起作用
    • @MukundKumar 不要那样做。只是import store from "./store"。您没有理由需要导出函数来创建商店。只需导入商店。如果你导出一个 create 函数并在多个文件中创建一个 store,你最终会得到多个 store。
    • 但我将 new Vuex.Store() 包装在 createStore 函数中。所以它应该可以工作。
    • @MukundKumar 你想要不止一家商店吗?
    • 对于遇到此问题的其他人-如果您使用模块,则必须导入基本存储并通过正斜杠符号引用模块,例如store.dispatch('user/markNotificationAsRead', notification);
    猜你喜欢
    • 2020-12-20
    • 2017-05-22
    • 1970-01-01
    • 2019-08-16
    • 1970-01-01
    • 2019-11-25
    • 2018-09-05
    • 1970-01-01
    • 2020-09-01
    相关资源
    最近更新 更多