因为mutations中是不能写异步的代码的,比如setTimeOut()等
比如我们需要数据隔几秒再发生变化,这种异步的代码我们只能写在action中。
我们在store/index.js中实现代码如下:
import Vue from "vue";
import Vuex from "vuex";
Vue.use(Vuex);
export default new Vuex.Store({
state: {
num: 0
},
mutations: {
addHandle(state) {
state.num++;
}
},
actions: {
addSync(context) {
setTimeout(() => {
context.commit("addHandle");
}, 1000);
}
},
modules: {}
});
Son1.vue中代码如下:
<template>
<div>
子组件1
<button @click="clickHandle">点击增加1</button>
<p>{{$store.state.num}}</p>
</div>
</template>
<script>
import { mapMutations } from "vuex";
export default {
data() {
return {};
},
methods: {
clickHandle: function() {
this.$store.dispatch("addSync");
}
}
};
</script>
此时点击按钮会隔一秒数据加一。
store/index.js中代码如下:
import Vue from "vue";
import Vuex from "vuex";
Vue.use(Vuex);
export default new Vuex.Store({
state: {
num: 0
},
mutations: {
addHandle(state, arg) {
state.num += arg;
}
},
actions: {
addSync(context, arg) {
setTimeout(() => {
context.commit("addHandle", arg);
}, 1000);
}
},
modules: {}
});
Son1.vue中代码如下:
<!-- 子组件1 -->
<template>
<div>
子组件1
<button @click="clickHandle">点击增加1</button>
<p>{{$store.state.num}}</p>
</div>
</template>
<script>
export default {
data() {
return {};
},
methods: {
clickHandle: function() {
this.$store.dispatch("addSync", 2);
}
}
};
</script>
store/index.js中代码如下:
import Vue from "vue";
import Vuex from "vuex";
Vue.use(Vuex);
export default new Vuex.Store({
state: {
num: 0
},
mutations: {
addHandle(state, arg) {
state.num += arg;
}
},
actions: {
addSync(context, arg) {
setTimeout(() => {
context.commit("addHandle", arg);
}, 1000);
}
},
modules: {}
});
Son1.vue中代码如下:
<!-- 子组件1 -->
<template>
<div>
子组件1
<button @click="clickHandle">点击增加1</button>
<p>{{$store.state.num}}</p>
</div>
</template>
<script>
import { mapActions } from "vuex";
export default {
data() {
return {};
},
methods: {
...mapActions(["addSync"]),
clickHandle: function() {
this.addSync(2);
}
}
};
</script>
getter主要是对store中的数据进行加工处理包装,不会修改store中的数据。
它类似于计算属性,store中的数据发生变化,getter中的数据也会发生变化。
import Vue from "vue";
import Vuex from "vuex";
Vue.use(Vuex);
export default new Vuex.Store({
state: {
num: 10
},
mutations: {
},
actions: {
},
getters: {
dataRes(state) {
return "修饰后的结果" + state.num;
}
},
modules: {}
});
<p>{{$store.getters.dataRes}}</p>
<!-- 子组件1 -->
<template>
<div>
子组件1
<p>{{dataRes}}</p>
</div>
</template>
<script>
import { mapGetters } from "vuex";
export default {
data() {
return {};
},
methods: {},
computed: {
...mapGetters(["dataRes"])
}
};
</script>