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函數中。所以它應該工作。 –