Skip to content

Instantly share code, notes, and snippets.

@lmiller1990
Created August 6, 2018 13:15
Show Gist options
  • Save lmiller1990/8a5cea45752e3692281b72ce08722b0b to your computer and use it in GitHub Desktop.
Save lmiller1990/8a5cea45752e3692281b72ce08722b0b to your computer and use it in GitHub Desktop.
Minimal Vuex from scratch (no package.json)
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="store.js"></script>
class Store {
static install(Vue) {
Vue.mixin({
beforeCreate() {
this.$store = this.$options.store
}
})
}
constructor({ state, mutations }) {
this.mutations = mutations
this.vm = new Vue({
data() {
return { $$state: state }
}
})
}
get state() {
return this.vm.$data.$$state
}
commit(handler, payload) {
this.mutations[handler](this.state, payload)
}
}
document.addEventListener("DOMContentLoaded", () => {
const el = document.createElement("div")
el.id = "app"
document.body.appendChild(el)
Vue.use(Store)
const mutations = {
increment(state, { amount }) {
state.count = state.count + amount
}
}
const store = new Store({ state: { count: 0 }, mutations })
window.app = new Vue({
el,
store,
template: `
<div>
{{ $store.state.count }}
<button @click="$store.commit('increment', { amount: 1 })">
Increment
</button>
</div>
`
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment