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

How to commit a mutation for sub-property in an action? #24

Closed maimake closed 6 years ago

maimake commented 6 years ago

I want to commit a mutation in an action, like store.set('page@status', 'loading') Is there any convenient way to do it ? Or could you export an function for that purpose ?

const state = {
    page: {
        status: '',
        data: []
    }
}
const mutations = make.mutations(state)
const actions = {
    foo({commit}) {
        commit('SET_PAGE', ??)
    }
}
maimake commented 6 years ago

Maybe 🤔

export function commitInAction(commit) {
  return function (path, value) {
    const [prop, subprop] = path.split('@')
    commit(`SET_${prop.toUpperCase()}`, new Payload(null, subprop, value))
  }
}
davestewart commented 6 years ago

Ah, I see what you're saying.

You want to commit to an pathify-generated mutation that handles payloads.

The additional issue is that you naming scheme may vary! (Pathify has code in it to work this out for you, maybe I should expose it).

At work right now, but can look at this when I get home :)

davestewart commented 6 years ago

The other option you have, is to import the store and use that:

import store from '../index'
const actions = {
    foo({commit}, value) {
        store.set('page@status', value)
    }
}

Remember that store.set() is added by Pathify to handle paths including sub-object commits 😃

You might also be able to use this in place of importing the store again. It works on my machine at work, not sure if it's universal as I've tried before and gotten undefined.

EDIT: OK, it seems like this in a store can be a variety of different things; certainly not reliable enough to use in this context

Someone else asked me if I could inject things into the handlers, but I don't think it's possible short of monkey-patching Vuex which isn't a good idea.

davestewart commented 5 years ago

See #79

gntzh commented 4 years ago

@davestewart

You might also be able to use this in place of importing the store again. It works on my machine at work, not sure if it's universal as I've tried before and gotten undefined.

EDIT: OK, it seems like this in a store can be a variety of different things; certainly not reliable enough to use in this context

Maybe it is works. Just use regular function rather than arrow function. I find an example in Vuex's issues. Vuex's developer offered a way to access store instance in action that using this and gave an example of axios in Nuxt.js. Vuex issue Nuxt.js

davestewart commented 4 years ago

@ShoorDay - ah, thanks! I'll have to take a look at this again