1. Basic knowledge
1. Do not perform asynchronous operations in Mutation.
But In some cases, we really want to perform some asynchronous operations in Vuex, such as network requests, which must be asynchronous. How to deal with this situation?
Action is similar to Mutation, but it is used to replace Mutation for asynchronous operations. The basic usage code of
Action is as follows:
[Related recommendations: vue.js video tutorial]
What is context?
(1) Context is an object with the same methods and properties as the store object.
(2) In other words, we can pass context to perform commit-related operations, you can also obtain context.state, etc.
2. Action method call
In the Vue component, if we call the action method, then you need to use dispatch
Similarly, it also supports passing payload
3. Action and Promise
In Action, we can put the asynchronous operation in a Promise, and after success or failure, call the corresponding resolve or reject
2. Effect
Call the method in action on the page
##3. Directory structure
4. Source code
index.jsimport { createStore} from 'vuex' export default createStore({ state: { counter: 0, info: { name: 'kobe', age: 40, height: 1.98 } }, mutations: { updateInfo(state) { state.info.name = 'coderwhy' } }, actions: { aUpdateInfo(context, payload) { return new Promise((resolve, reject) => { setTimeout(() => { context.commit('updateInfo'); console.log(payload); resolve('1111111') }, 1000) }) } }, getters: { }, modules: {} })
<template> <div > <h2>----------action: info对象的内容是否是响应式----------</h2> <h2>{{$store.state.info}}</h2> <button @click="updateInfo">修改信息</button> </div> </template> <script> import { computed } from 'vue' import { useStore } from 'vuex' export default { components: { }, methods: { updateInfo() { this.$store.dispatch('aUpdateInfo', '我是携带的信息') .then(res => { console.log('里面完成了提交'); console.log(res); }) }, }, setup() { return { } } } </script>
The above is the detailed content of Detailed explanation of Action asynchronous operation of Vuex state management. For more information, please follow other related articles on the PHP Chinese website!