vuex-type-helper

Type level helper to ensure type safety in Vuex
82,714
Install
npm install vuex-type-helper
Latest Version:1.3.1
Vue:2
License:MIT
Last Updated:Dec 14, 2020
Links: npm
Maintainer: ktsn

Vuex Type Helper

Type level helper to ensure type safety in Vuex.

Installation

# npm
$ npm install vuex-type-helper

# yarn
$ yarn add vuex-type-helper

Example

import * as Vuex from 'vuex'
import { DefineGetters, DefineMutations, DefineActions, Dispatcher, Committer } from 'vuex-type-helper'

/**
 * Declare module types
 */
export interface CounterState {
  count: number
}

export interface CounterGetters {
  // getterName: returnType
  half: number
}

export interface CounterMutations {
  // mutationName: mutationPayloadType
  inc: {
    amount: number
  }
  reset: void // having no payload
}

export interface CounterActions {
  // actionName: actionPayloadType
  incAsync: {
    amount: number
    delay: number
  }
  reset: void // having no payload
}

/**
 * Implement the module
 */
const state: CounterState = {
  count: 0
}

const getters: DefineGetters<CounterGetters, CounterState> = {
  half: state => state.count / 2
}

const mutations: DefineMutations<CounterMutations, CounterState> = {
  inc (state, { amount }) {
    state.count += amount
  },

  reset(state) {
    state.count = 0
  }
}

const actions: DefineActions<CounterActions, CounterState, CounterMutations, CounterGetters> = {
  incAsync ({ commit }, payload) {
    setTimeout(() => {
      commit('inc', payload)
    }, payload.delay)
  },

  reset({ commit }) {
    commit('reset')
  }
}

/**
 * Create a store as same as the ordinary way
 */
const store = new Vuex.Store({
  state,
  getters,
  mutations,
  actions
})

/**
 * Annotate dispatch/commit type with declared actions/mutations type
 */
store.dispatch<Dispatcher<CounterActions>>({
  type: 'incAsync',
  amount: 1,
  delay: 1000
})

store.dispatch<Dispatcher<CounterActions>>({
  type: 'reset'
})

store.commit<Committer<CounterMutations>>({
  type: 'inc',
  amount: 1
})

store.commit<Committer<CounterMutations>>({
  type: 'reset'
})

License

MIT

Related Packages

vuex-smart-module

Type safe Vuex module with powerful module features

78,801 372
vue-store

Some simple utilities for Vue.

7,296
vuex-basement

Vuex state persistance and synchronization between tabs/windows.

2,403
vuex-connect

A binding utility for a Vue component and a Vuex store.

7,667 250
@vuesion/addon-vuex-persist

vuesion vuex middleware to persist state + adapters

2,356 16

Version History

Version Released License
1.3.1 MIT
1.3.0 MIT
1.2.2 MIT
1.2.1 MIT
1.2.0 MIT