DEV Community

Discussion on: Build Vuex from scratch.

Collapse
 
benavern profile image
Benjamin CARADEUC

Hi!

I am very interested in this little implementation but can't get it to work.

I maybe did something wrong...

here is my modified implementation:

class Store {
  constructor (options = {}) {
    this._state = { ...options.state }
    this._actions = { ...options.actions }
    this._mutations = { ...options.mutations }
  }

  dispatch (action, payload) {
    if (!this._actions[action]) {
      throw new Error(`[Error] action ${action} is undefined`)
    }

    return this._actions[action](
      {
        commit: this.commit.bind(this),
        state: { ...this._state }
      },
      payload
    )
  }

  commit (type, payload) {
    if (!this._mutations[type]) {
      throw new Error(`[Error] mutation ${type} is undefined`)
    }

    return this._mutations[type].call(null, this._state, payload)
  }
}

function install (Vue) {
  Vue.$store = Vue.mixin({
    created () {
      if (this.$options.store) {
        this.$store = this.$options.store
      } else if (this.$options.parent && this.$options.parent.$store) {
        this.$store = this.$options.parent.$store
        Vue.util.defineReactive(this, 'state', this.$store)
      }
    }
  })
}

export default {
  install,
  Store
}

I can dispatch the actions, commit the mutations and I can see my state has been updated but I don't understant how to get the state value in my vue file :(

For example after mutating a users array in the state, I try to use this :

  • this.$store.state.users
  • this.$store.users
  • this.state.users

but neither of these are working...

Could you tell me what I'm doing wrong ?

Thanks!

Collapse
 
sadick profile image
Sadick

What do you get when you console.log(Vue.$store)?

Collapse
 
benavern profile image
Benjamin CARADEUC

I just modified this line and it worked Vue.util.defineReactive(this, 'state', this.$store._state)

Thread Thread
 
sadick profile image
Sadick • Edited

Nice to know that it worked.