vuex 和ajax,vue.js - vuex ajax call and several components - Stack Overflow

This article describes a few patterns for implementing ajax calls and updating vuex state. Personally I agree with the author that method 3 of moving your ajax calls to the vuex store as actions because, as the article points out, it decouples state and presentation logic. This is also helpful because you can return a promise from your action to know when the state can be mutated

Code example from the article:

store = new Vuex.Store({

state: {

message: ''

},

mutations: {

updateMessage(state, payload) {

state.message = payload

}

},

actions: {

refreshMessage(context) {

return new Promise((resolve) => {

this.$http.get('...').then((response) => {

context.commit('updateMessage', response.data.message);

resolve();

});

});

}

}

});

Vue.component('my-component', {

template: '

{{ message }}
',

methods: {

refreshMessage() {

this.$store.dispatch('refeshMessage').then(() => {

// do stuff

});

}

},

computed: {

message: { return this.$store.state.message; }

}

});

So as you can see here, ajax calls are encapsulated as vuex actions. In a component that relies on data from an ajax call, the component can perform the action (this.$store.dispatch('refreshMessage').then...) which will make the ajax call and update the data in the store. Since your component already has a reactive property that depends on data from the store, it will update automatically once the store has new data.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值