1
我有一个模块(javascript文件)在vue上下文之外。我需要从这个JavaScript文件调度行动。可能吗 ?如果是的话,那么如何?如何从javascript文件(而不是vue组件)调度动作?
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'导入{createStore}; const store = createStore(); store.dispatch('SET_LOCATION',{city:'California'}); 但它不起作用 –
@MukundKumar不要那样做。只需从“./store”进口商店。没有理由需要导出功能来创建商店。只需导入商店。如果您导出创建功能并在多个文件中创建商店,则最终将拥有多个商店。 – Bert
但我正在包装新的Vuex.Store()在createStore函数中。所以它应该工作。 –