Created
August 6, 2018 13:15
-
-
Save lmiller1990/8a5cea45752e3692281b72ce08722b0b to your computer and use it in GitHub Desktop.
Minimal Vuex from scratch (no package.json)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> | |
<script src="store.js"></script> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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