①State: 单一状态树,Vuex管理的状态对象,是唯一的。
定义的变量只能看到状态改变的结果,但是无法跟踪状态改变的过程。直接对$store. state的状态赋值是无法留痕的,此时就需要mutations。
案例:计数器(带参数)
//组件1
<button @click="$store.commit('add',8)">+8</button>
<span>数值:{{$store.state.count}}</span>
<button @click="$store.commit('sub',8)">-8</button>
//组件1
<button @click="$store.commit('add',8)">+8</button>
<span>数值:{{$store.state.count}}</span>
<button @click="$store.commit('sub',8)">-8</button>
//store
state: {
count:0
},
mutations: {
add(state,num){
state.count += num
},
sub(state,num){
state.count -= num
}
}
②Getter:包含对各计算属性的对象,组件使用$store. getters . xxx读取。
案例:名字
//组件1
<div>fullName:{{$store.getters.fullName}}</div>
//组件2
<div>fullName:{{$store.getters.fullName}}</div>
//App.vue
<div id="app">
<label for="firstName">firstName</label>
<input type="text" v-model="$store.state.firstName" id="firstName"/><br>
<label for="firstName">lastName</label>
<input type="text" v-model="$store.state.lastName" id="lastName"/>
<name1></name1>
<name2></name2>
</div>
<script>
import Name1 from '@/components/Name1'
import Name2 from '@/components/Name2'
export default {
name:'APP',
components:{
Name1,
Name2
},
cmounted:{
firstName:{
get(){
return this.$store.state.firstName
},
set(newVal){
this.$store.commit('handleFirstName',newVal)
}
},
lastName:{
get(){
return this.$store.state.lasttName
},
set(newVal){
this.$store.commit('handleLastName',newVal)
}
},
}
}
</script>
//store
state: {
firstName:'',
lastName:''
},
mutations: {
handleFirstName(state,payload){
state.firstName = payload
},
handleLastName(state,payload){
state.firstName = payload
}
},
getters:{
fullName(state){
console.log(state.firstName + '' + state.lastName)
return state.firstName + '' + state.lastName
}
}
③Mutation:包含多个直接更新state的方法(回调函数)的对象。由Action中commit( ' mutation名称' )触发。只能包含同步代码。对state状态进行操作的自定义方法,通过触发mutations方法修改的state可以留痕,可以被devtools调试工具跟踪。
④Action:包含多个事件回调函数的对象。通过执行commit( )触发mutation的调用,间接更新state。组件中的$store. dispatch( ' action名称',data )触发。可以包含异步代码。
Action的异步操作:在组件中使用dispatch触发异步操作Action。在异步操作Action中对Mutat ion操作进行commit 。
案例:名字
-
在上面的名字案例组件1中加一个按钮,store中添加代码。
//组件1
<button @click="$store.dispatch('sumbitAction')">异步操作</button>
//store
mutations: {
submitBtn(state){
state.firstName = 'hhhh'
}
}
actions: {
sumbitAction(context){
setTimeout(() => {
context.commit('submitBtn')
},1000)
}
}
⑤Module:包含多个module, 一个module是一个store的配置对象,与一个包含共享数据的组件对应。
注意点:
- mutation自定义方法里面必须是同步操作,因为异步回调无法有效被跟踪。
- devtools不能跟踪mutation的异步操作。