davestewart / vuex-pathify

Vue / Vuex plugin providing a unified path syntax to Vuex stores
https://davestewart.github.io/vuex-pathify
MIT License
1.37k stars 57 forks source link

Push / Splice array property mutations #127

Closed kdop closed 3 years ago

kdop commented 3 years ago

Hi,

First of all thank you for creating pathify, I trully appreciate it! However I am having some difficulty trying to understand how to work with arrays.

Consider this scenario:

const state = {
  tasks: [
    {
      id: 1,
      title: 'task 1',
    },
    {
      id: 2,
      title: 'task 2',
    }
  ]
}

const mutations = make.mutations(state)

This will give me the SET_tasks mutation for the state.tasks property. However I also need mutations to push, pop items in it:

PUSH_task = (state, payload) => {
    state.tasks.push(payload)
}

SPLICE_task = (state, index) => {
    state.tasks.splice(index, 1)
}

Does pathify support this? If not, how do you effectively deal with this situation?

davestewart commented 3 years ago

Hey!

Pathify doesn't support mutations like that, so you just let it create 1:1 mutations, then add yours after:

const mutations = {
  ...make.mutations(state),

  PUSH_TASK = (state, payload) => {
      state.tasks.push(payload)
  },

  SPLICE_TASK = (state, index) => {
      state.tasks.splice(index, 1)
  }
}
// results in
{
  SET_TASKS () { ... },
  PUSH_TASK () { ... },
  SPLICE_TASK () { ... },
}

You can actually pass various arguments to make() and it will derive properties so don't feel you have to pass in a whole state object; you can include some and miss out others:

const mutations = {
  ...make.mutations('bar baz'), // but not foo!

  PUSH_FOO = (state, payload) => {
      state.foo.push(payload)
  },
}

Hope that helps!