zoukankan      html  css  js  c++  java
  • Vuex之Action

    Action 类似于 mutation,不同在于:

    1. Action 提交的是 mutation,而不是直接变更状态。

    2. Action 可以包含任意异步操作。

    用Action处理异步操作示例:

    // 正常的mutation
    const increment = (state) => {
      state.count++
    }
    const decrement = (state) => {
      state.count--
    }
    export {increment, decrement}
    // action.js处理一些异步操作
    // Action 函数接受一个与 store 实例具有相同方法和属性的 context 对象
    let incrementAsync = (context) => {
      setTimeout(() => {
        context.commit('increment')
      }, 1000)
    }
    let decrementAsync = (context) => {
      setTimeout(() => {
        context.commit('decrement')
      }, 1000)
    }
    export {incrementAsync, decrementAsync}
    <template>
      <div>
        <button @click="decrementAsync">-</button>
        <span>{{count}}</span>
        <button @click="incrementAsync">+</button>
      </div>
    </template>
     
    <script>
    import { mapState, mapMutations, mapActions } from 'vuex'
    export default {
      computed: {
        ...mapState(['count'])
      },
      methods: {
        ...mapMutations(['increment', 'decrement']),
        ...mapActions(['incrementAsync', 'decrementAsync']) //这里用了辅助函数,不了解的可以看这个系列的第二篇文章
      }
    }
    </script>

    Action 通过store.dispatch方法分发:

    // 以载荷形式分发
    store.dispatch('incrementAsync', {
      amount: 10
    })
    
    // 以对象形式分发
    store.dispatch({
      type: 'incrementAsync',
      amount: 10
    })
  • 相关阅读:
    让unidac支持加密的sqlite
    hook api 保护进程
    Delphi实现网页采集
    UNIDAC
    Delphi的视频捕获组件
    删除程序自身
    一种简单的自校验的注册码生成方案以及暗桩方法
    SQL server表字段信息说明
    淘宝API开发(一)简单介绍淘宝API功能接口作用
    淘宝API开发(二)淘宝API接口功能测试
  • 原文地址:https://www.cnblogs.com/luoyihao/p/14746536.html
Copyright © 2011-2022 走看看