强行记忆: store中 所有的异步操作 必须放在actions内完成,不能放在mutations中(因为devtools无法监测mutations中的异步)

actions优雅结合promise

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    info: {
      name: 'why',
      age: 18,
      sex: '男'
    }
  },
  getters: {
  },
  mutations: {
    CHANGEINFONAME(state, payload) {
      state.info.name = payload
    }
  },
  actions: {
    // context: 上下文
    changeInfoName(context, payload) {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          context.commit('CHANGEINFONAME', payload)
          resolve('调接口获取参数成功!')
        }, 1000)
      })
    }
  },
  modules: {
  }
})

<template>
  <div class="debug">
      <div>{{$store.state.info}}</div>
      <div>
          <button @click="handleClick()">触发</button>
      </div>
  </div>
</template>

<script>
export default {
    methods:{
        handleClick() {
            this.$store.dispatch('changeInfoName', 'tm').then(res => {
                console.log(res);
            })
        }
    }
}
</script>
Logo

前往低代码交流专区

更多推荐