{{msg}}
{{$store.state.count}}
<button @click="$store.commit(‘add’)">+
<button @click="$store.commit(‘reduce’)">-
二、state访问状态对象
{{$store.state.count}}--{{count}}
目的:让$store.state.count的值赋给count,使用count直接显示结果
{{msg}}
{{$store.state.count}}--{{count}}
<button @click="$store.commit(‘add’)">+
<button @click="$store.commit(‘reduce’)">-
三、Mutations修改状态
- 传递参数
//操作变量的方法
const mutations={
add(state,n){
// state.count++;
state.count+=n;
},
reduce(state){
state.count–;
}
}
调用
<button @click="$store.commit(‘add’,10)">+
** 第一个参数书方法名,第二个参数书变量
- 修改方法:
a、引入:
//方式二 利用mapState这里注意mapState要加{},文档有坑
import {mapState, mapMutations} from ‘vuex’;
这里要加mapMutations
b、重写
methods:mapMutations([‘add’,‘reduce’]),
c、使用
<button @click=“reduce”>-
四、getters计算过滤操作
每次对state.count的操作都会经过这个过滤操作
store.js中操作
//getters计算过滤操作
const getters={
count:function(){
return state.count+=10;
}
}
// 外面使用需要进行暴露
export default new Vuex.Store({
state,
mutations,
getters
})
在模板中使用:
import { mapState, mapMutations, mapGetters}
computed: {
…mapState([‘count’]),
// count(){
// return this.$store.getters.count;
// }
…mapGetters([‘count’])
},
五、actions异步修改状态
在store.js中
// actions异步修改状态
const actions={
addAction(context){
context.commit(‘add’,10);
setTimeout(()=>{
context.commit(‘reduce’)
},3000);
},
reduceAction({commit}){
commit(‘reduce’);
}
}
// 外面使用需要进行暴露
export default new Vuex.Store({
state,
mutations,
getters,
在store.js中
// actions异步修改状态
const actions={
addAction(context){
context.commit(‘add’,10);
setTimeout(()=>{
context.commit(‘reduce’)
},3000);
},
reduceAction({commit}){
commit(‘reduce’);
}
}
// 外面使用需要进行暴露
export default new Vuex.Store({
state,
mutations,
getters,