如何通过接口请求来更新 Vuex store 的状态?
作者:互联网
1. 定义 Mutation
首先,在 store.js
或你的 Vuex 模块中定义一个 mutation,用于更新状态:
// store.js
const store = new Vuex.Store({
state: {
conversationList: []
},
mutations: {
UPDATE_CONVERSATION_LIST (state, conversations) {
state.conversationList = conversations;
}
},
actions: {
fetchConversations ({ commit }) {
// 假设你有一个 API 请求库,比如 axios
return axios.get('/api/conversations')
.then(response => {
commit('UPDATE_CONVERSATION_LIST', response.data);
})
.catch(error => {
console.error("Failed to fetch conversations:", error);
});
}
}
});
JavaScript
2. 调用 Action
在组件或其他地方调用这个 action 来触发接口请求:
// 在 Vue 组件中
methods: {
loadConversations () {
this.$store.dispatch('fetchConversations');
}
}
JavaScript
3. 使用 Mutation 更新特定 Conversation
如果你想在接收到新消息时更新特定的 conversation,可以在 mutation 中实现逻辑:
mutations: {
UPDATE_CONVERSATION_LIST (state, conversations) {
state.conversationList = conversations;
},
ADD_MESSAGE_TO_CONVERSATION (state, { conversationId, message }) {
const conversation = state.conversationList.find(conversation =>
conversation.SessionId === conversationId
);
if (conversation) {
conversation.updateLastMessageList(message); // 确保 conversation 对象有此方法
console.log("ADD_MESSAGE ", JSON.stringify(conversation, null, 2));
}
}
}
JavaScript
4. 调用 Mutation
当你接收到新消息时,可以通过 dispatch action 来调用 mutation:
actions: {
addMessage ({ commit }, { conversationId, message }) {
commit('ADD_MESSAGE_TO_CONVERSATION', { conversationId, message });
}
}
JavaScript
5. 在组件中调用
methods: {
handleNewMessage (message) {
this.$store.dispatch('addMessage', {
conversationId: message.ReceiverId || message.mImReceiverId,
message: message
});
}
}
JavaScript
标签: 来源: