Vuex 的异步数据更新(小记)

更改 Vuex 的 store 中的状态的唯一方法是提交 mutation。Vuex 中的 mutation 非常类似于事件:每个 mutation 都有一个字符串的 事件类型 (type) 和 一个 回调函数 (handler)。这个回调函数就是我们实际进行状态更改的地方,并且它会接受 state 作为第一个参数
mutation 是同步执行,不是异步执行。

由于Mutations不接受异步函数,要通过Actions来实现异步请求。
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 的方法
    })
};
在Mutations中通过putSSS接收并更新style数据:
export const putSSS=(state, val) => {
    state.style = val;
};

组件创建时更新数据,写在 created 中

this.$store.dispatch('setStyle',{
    id:this.id,
    name: this.name,
    });

使用 mapActions

使用 mapActions 辅助函数将组件的 methods 映射为 store.dispatch 调用(需要先在根节点注入 store)

methods: {
    ...mapActions([
        'setStyle'
    ]),
    test(){
    // 映射后可直接使用方法,不需要写 this.$store.dispatch
     this.setStyle({
         id:this.id,
        name: this.name,
     });
    }
}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值