vuejs / vuex

🗃️ Centralized State Management for Vue.js.
https://vuex.vuejs.org
MIT License
28.41k stars 9.57k forks source link

Automatically create mutations for each store variable #91

Closed thelinuxlich closed 8 years ago

thelinuxlich commented 8 years ago

It would be nice to have a option to enable this behavior.

YerkoPalma commented 8 years ago

This make sense for me. I was creating an object for the store, and it's mutations, something like this

const state = {
  accounts: {}
}

const mutations = {
  SET_ACCOUNTS (state, accounts) {
    state.accounts = accounts
  },
  ADD_ACCOUNT (state, account) {
    state.accounts.push(account)
  },
  DELETE_ACCOUNT (state, account) {
    state.accounts.$remove(account)
  }
}

and I have other objects like this, so it would be awesome to declare some mutations generators for those objects. I think that an option could be like this.

export default new Vuex.Store({
  state: {
    data: state,
    generators: {
      type: 'CRUD',
      on: 'all'
    }
  },
  mutations
})

This would generate four mutations CREATE_<state-object>, READ_<state-object>, UPDATE_<state-object> and DELETE_<state-object>. In the generator option it could be added a different string specifying the operation, for example a type of 'RU' would only add the mutations fro READ and UPDATE. It will also allow to specify for which objects of the state generate the basic mutations with the on property. also notice that the mutations propertie is still present and should take precedence over the automatically generated mutations, so if a CREATE_ACCOUNT mutation is present on the mutation property, it would overwrite the auto generated CREATE_ACCOUNT property

yyx990803 commented 8 years ago

This could easily be done in userland with functions that return Vuex options - I don't think it should be in Vuex itself:

export default new Vuex.Store({
  state: {
    accounts: []
  },
  mutations: Object.assign(generateCRUDMutationsFor('accounts'), {
    // ... other mutations
  })
})
pksunkara commented 7 years ago

Is there any library which does this? I can work on one if not.

lmiller1990 commented 6 years ago

@pksunkara You can do this without a lib, just a few helper functions. I made an example: https://github.com/lmiller1990/vuex-async

pksunkara commented 6 years ago

Yeah, but it would be nice to have an open source lib people can use instead of duplicating code and efforts.

lmiller1990 commented 6 years ago

I'm interested. I do agree this shouldn't be in the core vuex. Get in touch and we talk about what kind of API and we can get started on something. I'm sure other would use such a lib. Join the Vue-land discord and shoot me a msg at Lachlan#8352.