为什么要使用actions?
3步骤告诉你结果:
为什么要使用actions-差异化展示第1步:在index.js里面添加方法,模拟异步
为什么要使用actions-差异化展示第2步:在About.vue里面添加异步按钮
为什么要使用actions-差异化展示第3步:在About.vue里面设置异步方法
首先要安装插件:vue.js devtools
异步延迟+1
index.js代码:
// store/index.js内容
import Vue from 'vue'
//1.导入模块
import Vuex from 'vuex'
//2.使用当前的插件
Vue.use(Vuex)
const store = new Vuex.Store({
state: { //当前的状态
count:0 //vuex的基本使用第一步:设置数量count.
},
getters: { //store的计算属性
},
mutations: { //声明同步的方法,只能是同步方法。
increment(state){ //vuex的基本使用第七步:修改状态。
//修改状态
state.count++
},
decrement(state){
state.count--
},
incrementAsync(state){ //为什么要使用actions-差异化展示第1步:在index.js里面添加方法,模拟异步
setTimeout(()=>{
state.count++;
},1000);
}
// incrementAsync(state){
// state.count++;
// }
},
actions: { //声明异步的方法
// increment({commit}){ //vuex的基本使用第六步:声明Increment方法
// //commit mutations中声明的方法
// //修改状态的唯一方法是提交mutation
// commit('increment')
// },
// decrement({commit}){
// commit('decrement')
// }
// incrementAsync({commit}){
// setTimeout(()=>{
// commit('incrementAsync');
// },1000);
// }
},
modules: {
}
})
export default store;
//4.17 vuex的其本使用8步骤:
//vuex的基本使用第1步:在/store/index.js里面设置数量count.
//vuex的基本使用第2步:在About.vue里面设置计算属性的值。
//vuex的基本使用第3步:在About.vue里面设置显示count。
//vuex的基本使用第4步:在About.vue里面设置+1按钮
//vuex的基本使用第5步:在About.vue里面设置声明increment方法
//vuex的基本使用第6步:在/store/index.js里面设置Increment方法
//vuex的基本使用第7步:在/store/index.js里面设置修改状态。
//vuex的基本使用第8步:在App.vue上设置使用。
//4.18为什么要使用actions-差异化展示3步:
//为什么要使用actions-差异化展示第1步:在index.js里面添加方法,模拟异步
//为什么要使用actions-差异化展示第2步:在About.vue里面添加异步按钮
//为什么要使用actions-差异化展示第3步:在About.vue里面设置异步方法
About.vue代码:
// About.vue内容
<template>
<div class="about">
<h1>This is an about page</h1>
{{count}} <!-- //vuex的基本使用第三步:显示count -->
<button @click="increment">+1</button> <!-- //vuex的基本使用第四步:设置+1按钮 -->
<button @click="decrement">-1</button>
<button @click="incrementAsync">+1异步</button> <!-- 为什么要使用actions-差异化展示第2步:在About.vue里面添加异步按钮 -->
</div>
</template>
<script>
export default{
computed: { //vuex的基本使用第二步:设置计算属性的值。
count() {
return this.$store.state.count //获取count值。实时监听count的变化。
}
},
methods:{ //vuex的基本使用第五步:声明increment方法
incrementAsync(){ //为什么要使用actions-差异化展示第3步:在About.vue里面设置异步方法
this.$store.commit('incrementAsync');
},
increment(){
//dispatch触发actions中声明的方法
// this.$store.dispatch('increment');
this.$store.commit('increment');
},
decrement(){
// this.$store.dispatch('decrement');
this.$store.commit('decrement');
}
}
}
</script>
运行结果: