2017-10-12 51 views
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, 
    }); 
} 

回答

2

首先,在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实例的主要或索引文件,你现在有可能需要进口,从进口的创造功能简单地导入存储更改。

+0

我这样做: 从'../store'导入{createStore}; const store = createStore(); store.dispatch('SET_LOCATION',{city:'California'}); 但它不起作用 –

+0

@MukundKumar不要那样做。只需从“./store”进口商店。没有理由需要导出功能来创建商店。只需导入商店。如果您导出创建功能并在多个文件中创建商店,则最终将拥有多个商店。 – Bert

+0

但我正在包装新的Vuex.Store()在createStore函数中。所以它应该工作。 –