[Vuejs]-Creating a mini store with property getters used Vue.observable

0👍

To create your store getters (similar to Vuex’s getters) from a given getters map:

  1. Declare a new object to store our new getters (named myGetters).
  2. Use Object.entries() on getters to get its keys and values.
  3. On each key/value pair, use Object.defineProperty() on myGetters to define a getter that invokes the value (if it’s a function) with state as the argument.
function createStore({ state, mutations, getters }) {
  1️⃣
  const myGetters = {}

  if (getters) {
    2️⃣
    Object.entries(getters).forEach(([key, value]) => {
      3️⃣
      Object.defineProperty(myGetters, key, {
        get: () => typeof value === 'function' ? value(state) : value
      })
    })
  }

  return {
    //...
    getters: myGetters
  }
}

Then initialize it in store.js like this:

const store = createStore({
  //...
  getters: {
    counter: state => state.counter,
    half: state => state.counter / 2,
    double: state => state.counter * 2,
    square: state => Math.pow(state.counter, 2)
  }
})

demo

Leave a comment