笔记
正常情况下,≥2个组件使用Vuex才有意义,但是本例为了搞明白Vuex,只使用了一个组件Count.vue,将来其它组件同理。
重要文件源码
store\index.js
//该文件用于创建Vuex中最为核心的store
import Vue from 'vue'
//引入Vuex
import Vuex from 'vuex'
//使用Vuex插件
//注意:
// 保证 Vue.use(Vuex) 要放在 new .Store()对象前面。 否则会提示: Uncaught Error: [vuex] must call Vue.use(Vuex) before creating a store instance.
Vue.use(Vuex)
//相当于 服务员
//准备actions --- 用于 响应组件中的动作
const actions = {
//context 是一个 miniStore,可以简单理解为一个 mini版的 Store,其中包含 .commit()函数
//value 是传递过来的参数.
//由于本例中 jia() 和 jian() 随手通过 context.commit() 提交走了,中间也没干啥事, 所以可以跳过 .dispatch() ,直接让 .vue 使用 .commit()
/*jia(context,value){
console.log('actions中的jia被调用了')
//继续通过 .commit() 往下级提交给 Mutations对象
//一般将commit(第0个参数,第1个参数),中的第0个参数表示的方法名大写,即 .commit('大写',value),一看大写就是 mutations对象中的,因为 mutation可以直接操作 state,所以 mutation比较厉害。
context.commit('JIA',value)
},
jian(context,value){
console.log('actions中的jian被调用了')
context.commit('JIAN',value)
}, */
jiaOdd(context,value){
console.log('actions中的jiaOdd被调用了',context) //上下文 content 中也可以找到 state
if(context.state.sum % 2){
context.commit('JIA',value)
}
},
jiaWait(context,value){
console.log('actions中的jiaWait被调用了')
setTimeout(()=>{
context.commit('JIA',value)
},500)
}
}
//相当于 后厨
//准备mutations --- 用于 操作(修改/加工/维护)状态数据(state)
const mutations = {
//state 是 Vuex 中的 state
//value 是传递过来的参数.
JIA(state,value){
console.log('mutations中的JIA被调用了')
state.sum += value
},
JIAN(state,value){
console.log('mutations中的JIAN被调用了')
state.sum -= value
}
}
//相当于 食材
//准备state --- 用于 存储数据
const state = {
sum:0 //当前的和
}
//vm new Vue()
//创建 store
/*const store = new Vuex.Store({ //需要传入配置对象
actions:actions,
mutations:mutations,
state:state,
})*/
//简写:
//创建并暴露store 此处∈默认暴露
export default new Vuex.Store({
//3个配置项
actions,
mutations,
state,
})components\Count.vue
<template>
<div>
<!-- 此处不用写为 this.$store.state.sum ,因为 模板中能看到 vc 中的所有东西 -->
<h1>当前求和为:{{$store.state.sum}}</h1>
<select v-model.number="n">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<button @click="increment">+</button>
<button @click="decrement">-</button>
<button @click="incrementOdd">当前求和为奇数再加</button>
<button @click="incrementWait">等一等再加</button>
</div>
</template>
<script>
export default {
name:'Count',
data() {
return {
n:1, //用户选择的数字
}
},
methods: {
increment(){
//this 指 vc
//this.$store.dispatch('jia',this.n)
//直接使用 .commit() 给 mutations对象
this.$store.commit('JIA',this.n)
},
decrement(){
//this.$store.dispatch('jian',this.n)
this.$store.commit('JIAN',this.n)
},
incrementOdd(){
this.$store.dispatch('jiaOdd',this.n)
},
incrementWait(){
this.$store.dispatch('jiaWait',this.n)
},
},
mounted() {
console.log('Count',this)
},
}
</script>
<style lang="css">
button{
margin-left: 5px;
}
</style>
