import Vuex from './vuex' // 引入我们的自己编写的文件
Vue.use(Vuex) // 安装store
// 实例化store,参数数对象
export default new Vuex.Store({
state: {
count : 1000
},
getters : {
newCount (state) {
return state.count + 100
}
},
mutations: {
change (state) {
console.log(state.count)
state.count += 10
}
},
actions: {
change ({commit}) {
// 模拟异步
setTimeout(() => {
commit('change')
}, 1000)
}
}
})
配置选项都写好之后,就看到
getters对象里面有个
newCount函数,
mutations和
actions对象里面都有个
change函数,配置好
store之后我们在
App.vue就可以写上,
dispatch和
commit,分别可以触发
actions和
mutations,代码如下
<template>
<div id="app">
这里是store的state------->{{this.$store.state.count}} <br/>
这里是store的getter------->{{this.$store.getters.newCount}} <br/>
<button @click="change">点击触发dispach--> actions</button>
<button @click="change1">点击触发commit---> mutations</button>
</div>
</template><script>
export default {
name: 'app',
methods: {
change () {
this.$store.dispatch('change') // 触发actions对应的change
},
change1 () {
this.$store.commit('change') // 触发mutations对应的change
}
},
mounted () {
console.log(this.$store)
}
}
</script>
数据都配置好之后,我们开始编写store类,在此之前我们先编写一个循环对象工具函数。
const myforEach = (obj, callback) => Object.keys(obj).forEach(key => callback(key, obj[key]))
// 作用:
// 例如{a: '123'}, 把对象的key和value作为参数
// 然后就是函数运行callback(a, '123')工具函数都准备好了,之后,下面直接县编写
getters、
mutations和
actions的实现
class Store {
constructor (options) {
let { state = {}, getters = {}, actions = {}, mutations = {} } = options










