import Vue from 'vue'
import App from './App.vue'
Vue.config.productionTip = false
import store from './store'
new Vue({
store: store,
render: h => h(App),
}).$mount('#app')
import Vuex from '../vuex'
import Vue from 'vue'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
count: 1
},
getters: {
doubleCount: state => {
return state.count * 2
}
},
mutations: {
increment (state) {
state.count++
}
},
actions: {
incrementAsync (context) {
setTimeout(() => {
context.commit('increment')
}, 1000);
}
}
})
let Vue;
class Store {
constructor(options) {
this.state = new Vue({
data: options.state
})
this.mutations = options.mutations
this.actions = options.actions
this.commit = this.commit.bind(this)
this.dispatch = this.dispatch.bind(this)
this.getters = {}
if (options.getters) {
this.handleGetters(options.getters)
}
}
handleGetters (getters) {
Object.keys(getters).forEach(key => {
Object.defineProperty(this.getters, key, {
get: () => {
return getters[key](this.state)
}
})
})
}
commit (fnKey, payload) {
const mutationsFn = this.mutations[fnKey]
mutationsFn(this.state)
}
dispatch (fnKey, payload) {
const actionsFn = this.actions[fnKey];
actionsFn(this, payload)
}
}
const install = (_Vue) => {
Vue = _Vue;
Vue.mixin({
beforeCreate () {
if (this.$options.store) {
Vue.prototype.$store = this.$options.store
}
},
})
}
export default {
install, Store
}
<template>
<div id="app">
<img alt="Vue logo" src="./assets/logo.png">
<p>count:{{$store.state.count}}</p>
<p>doubleCount:{{$store.getters.doubleCount}}</p>
<button @click="$store.commit('increment')">setCount</button>
<button @click="$store.dispatch('incrementAsync')">setCountAsync</button>
</div>
</template>
<script>
export default {
name: 'App',
components: {
}
}
</script>
<style>
</style>