Home  >  Article  >  Web Front-end  >  Detailed explanation of Action asynchronous operation of Vuex state management

Detailed explanation of Action asynchronous operation of Vuex state management

藏色散人
藏色散人forward
2022-08-10 15:29:434648browse

action usage

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.js

import { 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: {}
})

App.vue

<template>
    <div >
        <h2>----------action: info对象的内容是否是响应式----------</h2>
        <h2>{{$store.state.info}}</h2>
        <button @click="updateInfo">修改信息</button>
    </div>
</template>
 
<script>
    import {    computed } from &#39;vue&#39;
    import {    useStore } from &#39;vuex&#39;
    export default {
        components: {
        },
        methods: {
            updateInfo() {
              this.$store.dispatch(&#39;aUpdateInfo&#39;, &#39;我是携带的信息&#39;)
                .then(res => {
                  console.log(&#39;里面完成了提交&#39;);
                  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!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete