vuex 创建 action 工具库——vuex-action

1,918 阅读1分钟

Utilities for vuex to create action.

Support for vue@1 and vue@2

Installation

  npm install --save vuex-action

Usage

  import {createAction} from 'vuex-action'

createAction([type], [payloadHandler])

It creates an action, and the action type will generated by uuidV4() if not specified.

  // Create an action
  const increment = createAction('ACTION_TYPE')
  // Or
  const increment = createAction()
  // PayloadHandler allows you to customize the payload
  const add = createAction((num) => num || 1)
  // Therefore
  this.add() // +1
  this.add(5) // +5
  // Or
  const fetchUserApi = function (name) {
    return Promise.resolve({username: name})
  }
  // Return a Promise
  const fetchUser = createAction((name) => fetchUserApi(name))
  this.fetchUser('Harrie') // payload = {username: 'Harrie'}
  // The store
  const store = new Vuex.Store({
    state: {
      count: 0,
      user: null
    },
    mutations: {
      // just make it as a type
      [increment] (state, num) {
        state.count += num
      },
      [fetchUser] (state, user) {
        state.user = user
      }
    }
  })

Inspired by