更改 Vuex 的 store 中的状态的惟一方法是提交 mutation。Vuex 中的 mutation 很是相似于事件:每一个 mutation 都有一个字符串的 事件类型 (type) 和 一个 回调函数 (handler)。这个回调函数就是咱们实际进行状态更改的地方,而且它会接受 state 做为第一个参数
mutation 是同步执行,不是异步执行。ios
export const setAddPurchaseStyle = ({commit, state}, obj) => { url='http://xxx.com' + '/json/' + '/development' + '/purchaserexp/create_company.js'; let _tempObj={}; // 着键是这个 return return new Promise(function(resolve, reject) { axios.get(url, {}).then((response) => { resolve('请求成功后,传递到 then'); }, (response) => { //失败 console.info('error', response); reject('请求失败后,传递到 catch') }); }).then((res)=>{ // res 是 (请求成功后,传递到 then) commit('putSSS', Math.random()); // 在Promise的成功中,调用 mutations 的方法 }) };
export const putSSS=(state, val) => { state.style = val; };
this.$store.dispatch('setStyle',{ id:this.id, name: this.name, });
使用 mapActions 辅助函数将组件的 methods 映射为 store.dispatch 调用(须要先在根节点注入 store)json
methods: { ...mapActions([ 'setStyle' ]), test(){ // 映射后可直接使用方法,不须要写 this.$store.dispatch this.setStyle({ id:this.id, name: this.name, }); } }