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
    })
  • 相关阅读:
    redis+nginx+tomcat故障大全
    Nginx+Tomcat+Redis实现负载均衡、资源分离、session共享
    Redis初步认识
    私有IP地址共有三个范围段
    公有云和私有云的区别
    svn安装与其服务器搭建
    datagrid后台分页js
    easyui.dialog.js
    EasyUI 另一种form提交方式
    easyui- grid前台分页
  • 原文地址:https://www.cnblogs.com/luoyihao/p/14746536.html
Copyright © 2011-2022 走看看