fengchuanyu 3 months ago
parent
commit
2c15f8d67d
2 changed files with 48 additions and 3 deletions
  1. 25 0
      12_vuecli/myapp/src/store/index.js
  2. 23 3
      12_vuecli/myapp/src/views/AboutView.vue

+ 25 - 0
12_vuecli/myapp/src/store/index.js

@@ -3,20 +3,45 @@ import Vuex from 'vuex'
 
 Vue.use(Vuex)
 
+let user = {
+  state:{
+    count:10000
+  },
+  mutations:{
+    addUser(state){
+      state.count++
+    }
+  }
+}
+
 export default new Vuex.Store({
+  // state 状态值
   state: {
     stateNum:100,
     stateStr:'hello world'
   },
+  // getters 类似于计算属性computed
   getters: {
+    getterNum(state){
+      return state.stateNum + 1000
+    }
   },
+  // mutations 用来处理同步操作 同步修改状态值
   mutations: {
     stateNumAdd(state,i){
       state.stateNum+=i
+    },
+    stateNumReduce(state){
+      state.stateNum-=1
     }
   },
+  // actions 用来处理异步操作 异步修改状态值
   actions: {
+    actionHandle({commit}){
+      commit('stateNumAdd',5);
+    }
   },
   modules: {
+    userModule:user
   }
 })

+ 23 - 3
12_vuecli/myapp/src/views/AboutView.vue

@@ -5,22 +5,42 @@
     <h1>当前页面状态值:{{thisVal}}</h1>
     <h1>mapState的值:{{stateNum}}</h1>
     <h1>mapStateStr的值:{{stateStr}}</h1>
-    <button @click="changeFun">changeState</button>
+    <!-- <h1>getters的值:{{$store.getters.getterNum}}</h1> -->
+    <h1>getters的值:{{getterNum}}</h1>
+
+    <!-- <button @click="changeFun">changeState</button> -->
+    <button @click="stateNumAdd(100)">changeState</button>
+
+    <!-- <button @click="$store.commit('stateNumReduce')">减法操作</button> -->
+    <button @click="stateNumReduce">减法操作</button>
+
+    <!-- <button @click="actionFun">actionHandle</button> -->
+    <button @click="actionHandle">actionHandle</button>
+
+    <h1>用户模块:{{$store.state.userModule.count}}</h1>
+    <button @click="$store.commit('userModule/addUser')">用户模块加法操作</button>
   </div>
 </template>
 <script>
-import {mapState} from 'vuex';
+import {mapState,mapMutations,mapGetters,mapActions} from 'vuex';
 export default {
   methods: {
+    ...mapMutations(['stateNumAdd',"stateNumReduce"]),
+    ...mapActions(['actionHandle']),
     changeFun(){
       console.log(this.$store.state.stateNum);
       // this.$store 可以获取当前vuex对象的
       // 通过commit方法调用store/index.js中mutations中方法
       // 接收多个参数,第一个是mutations中方法名,第二个开始是传入的参数
-      this.$store.commit("stateNumAdd",10);
+      // this.$store.commit("stateNumAdd",10);
+
+    },
+    actionFun(){
+      this.$store.dispatch("actionHandle");
     }
   },
   computed:{
+    ...mapGetters(['getterNum']),
     ...mapState(['stateNum','stateStr']),
     thisVal(){
       return this.$store.state.stateNum