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
    })
  • 相关阅读:
    深入理解hadoop之MapReduce
    centos关机与重启命令
    hadoop学习笔记(1)
    配置ssh免密码登录设置后还是提示需要输入密码
    js获得URL中的参数
    SQLite介绍
    sql记录
    sql游标使用
    sql触发器
    sql函数
  • 原文地址:https://www.cnblogs.com/luoyihao/p/14746536.html
Copyright © 2011-2022 走看看