vuexed-objects

0.3.1 • Public • Published

Vuexed Objects

npm pipeline status npm

Motivation

Suppose that you have a list of objects in your Vuex Store:

const store = new Store({
  state: {
    objects: [
      {field: value},
      // ...
    ]
  }
})

You need to modify these values, but the store is not updated when you set the value normally:

store.state.objects[i].field = newValue

Or maybe you want to use the field in v-model:

<template>
  <component
    v-model="$store.state.objects[i].field
  />
</template>

This is especially annoying when you are using plugins that rely on mutation subscriptions to work, such as vuex-persistedstate.

The official vuex guide recommends to use a 2-way computed property, which does work, but still requires a lot of boilerplate code. The computed properties could be mixed in but you would still have to write mutations for each field.

There are existing libraries that try to fix this problem such as vuex-map-fields. However they reuse a single mutation for multiple fields and then you lose the benefit of verbosity and nice devtool features. Additionally, this approach does not work when setting the field outside a Vue component.

Goal

What this library tries to accomplish is a way to have all the benefits of regular vuex mutations (such as verbosity, time travel, reverting commits) and none of the burden of boilerplate code.

It makes sense to group similarly structured objects into their own module but this library does not enforce such groupings. You are responsible for grouping objects together with informative module names.

This library tries to be as configurable as possible so that it can be integrated into as many different environments as possible.

How It Works

For each field in an object, a mutation is created and a custom setter is created which invokes that mutation. A module is then built with those generated mutations and the objects at its state.

Each generated mutation is just an empty arrow function, but the value being set on the object's field is still passed to the commit function as the payload so that devtool features work as expected.

The custom setter respects any previous custom setters so it should not interfere with Vue's observer functionality.

A single additional mutation is added to the module which can be used to add objects to the module. Objects added in this manner also have their enumerable properties' setters replaced with custom setters which invoke the appropriate mutations.

In order to support properties that were not present on the objects at the initial module creation, a hotUpdateModule function can be passed in which will be invoked with the updated module in the case where additional mutations are added. This updated module can be passed to the Vuex store's hotUpdate function to achieve a dynamic module.

Installation

NPM

npm install vuexed-objects --save

yarn

yarn add vuexed-objects

CDN

<script src="https://unpkg.com/vuexed-objects/dist/vuexed-objects.js"></script>

Usage

You are responsible for adding the module to the store yourself. The main entrypoint is the function buildModule but addReactivity is also exported in the hope that it will be useful.

Static Modules

The simplest way to use this library is to build a static module. A static module will only have the mutations created at the initial call to buildModule. Adding objects will make them reactive but only for those initial mutations.

Static registration

import {Store} from 'vuex'
import {buildModule} from 'vuexed-objects'
import state from './state'
import getters from './getters'
import actions from './actions'
import mutations from './mutations'
import modules from './modules'
 
const obj0 = {a: 5, b: 2}
const obj1 = {a: 7, b: 6}
 
// declare the variable up here so that it is available in the correct scope
let store
 
store = new Store({
  state,
  mutations,
  actions,
  getters,
  modules: {
    ...modules,
    myModuleName: buildModule({
      objects: [
        obj0,
        obj1,
      ],
      path: 'myModuleName',
      store,
    })
  }
})
 
obj0.a = 1 // will trigger mutation myModuleName/a with payload {value: 1}
 
const obj2 = {a: 1, b: 0, c: 3}
 
// we can add objects to the module with a special mutation
store.commit('myModuleName/$add', obj2)
 
obj2.b = 4 // will trigger mutation myModuleName/b with payload {value: 4}
obj2.c = 2 // will not trigger any mutations since we used a static module

Dynamic registration with nested module

// ...
 
store.registerModule(
  ['my', 'nested', 'module'],
  buildModule({
    objects: [
      obj0,
      obj1,
    ],
    path: 'my/nested/module',
    store,
  })
)

Dynamic Modules

Its possible to have mutations added to the module as objects when new properties are added. You must pass in hotModuleUpdate to buildModule in order to enable this feature. hotModuleUpdate will be called when new mutations are added with the updated module passed in as the only argument.

You need to update the store (presumably using store.hotUpdate) to use the updated module. Special care must be taken when using this in conjunction with hot module replacement. You need to make sure that the module that you are passing into store.hotUpdate in your HMR function is always the updated version.

import {Store} from 'vuex'
import {buildModule} from 'vuexed-objects'
import state from './state'
import getters from './getters'
import actions from './actions'
import mutations from './mutations'
import modules from './modules'
 
const obj0 = {a: 5, b: 2}
const obj1 = {a: 7, b: 6}
 
// declare the variables up here so that they are available in the correct scope
let store, vuexedModule
 
vuexedModule = buildModule({
  objects: [
    obj0,
    obj1,
  ],
  path: 'myModuleName',
  store,
  hotModuleUpdate: module => {
    // we update the variable here so that the updated module will be available to the HMR function
    vuexedModule = module
    // update the store with the updated module
    store.hotUpdate({
      modules: {
        // spread in your other modules or else they will be deleted
        ...modules,
        myModuleName: module,
      }
    })
  }
})
 
store = new Store({
  state,
  mutations,
  actions,
  getters,
  modules: {
    ...modules,
    myModuleName: vuexedModule,
  }
})
 
if (module.hot) {
  module.hot.accept([
    './getters',
    './actions',
    './mutations',
    './modules',
  ], () => {
    store.hotUpdate({
      getters: require('./getters').default,
      actions: require('./actions').default,
      mutations: require('./mutations').default,
      modules: {
        // spread your modules in
        ...(require('./modules').default) // parentheses to be safe?
        // vuexedModules here was updated in hotModuleUpdate so we are g2g
        myModuleName: vuexedModules,
      },
    })
  })
}
 
obj0.a = 1 // will trigger mutation myModuleName/a with payload {value: 1}
 
const obj2 = {a: 1, b: 0, c: 3}
const obj3 = {c: 4, d: 5}
 
// we can add objects to the module with a special mutation
store.commit('myModuleName/$add', [obj2, obj3])
 
obj2.b = 4 // will trigger mutation myModuleName/b with payload {value: 4}
obj2.c = 2 // will now trigger myModuleName/c since we used dynamic module

API

See API.md

Caveats

Nested objects will not vuexed. You must explicitly call buildModule for each list of objects that you want to be vuexed. This may be added in a future release.

Contributing

Feedback and merge requests are welcome!

Readme

Keywords

Package Sidebar

Install

npm i vuexed-objects

Weekly Downloads

0

Version

0.3.1

License

MIT

Unpacked Size

37.5 kB

Total Files

6

Last publish

Collaborators

  • griest