• vuex-Actions的用法


    Action 类似于 mutation,不同在于:

    Action 提交的是 mutation,而不是直接变更状态. Action 是异步的,mutation是同步的。

    沿用vuex学习---简介的案例:这里是加10 减1

    1.在store.js 中 代码为:

    import Vue from 'vue'
    import Vuex from 'vuex'
     
    //使用vuex模块
    Vue.use(Vuex);
     
    //声明静态常量为4
    const state = {
      count : 4
    };
     
    const mutations = {
      add(state,n){
        state.count +=n.a;
      },
      sub(state){
        state.count--;
      }
    };
     
    const actions = {
      //2种书写方式
      addplus(context){ //可以理解为代表了整个的context
        context.commit('add',{a:10})
      },
      subplus({commit}){
        commit('sub');
      }

    };
     
    //导出一个模块
    export default new Vuex.Store({
      state,
      mutations,
      actions
    })

    2.在App.vue中 代码如下:

    <template>
     <div id="app">
       <div id="appaaa">
        <h1>这是vuex的示例</h1>
     
        <p>组件内部count{{count}}</p>
        <p>
          <button @click = "addplus">+</button>
          <button @click = "subplus">-</button>
        </p>
        </p>
     
      </div>
     </div>
    </template>
     
    <script>
    //引入mapGetters
    import {mapState,mapMutations,mapGetters,mapActions} from 'vuex'
    export default {
     name:'app',
     data(){
       return {
          
       }
     },
     computed:{
       ...mapState([
         "count"
         ]),
     },
     methods:{
       ...mapActions([
          "addplus",
          "subplus"
         ])
     }
     
    }
    </script>
     
    <style>
     
    </style>
  • 相关阅读:
    VS2010 自动跳过代码现象
    Reverse Linked List II 【纠结逆序!!!】
    Intersection of Two Linked Lists
    Linked List Cycle II
    Remove Nth Node From End of List 【另一个技巧,指针的指针】
    Swap Nodes in Pairs
    Merge Two Sorted Lists
    Remove Duplicates from Sorted List
    Linked List Cycle
    Dungeon Game
  • 原文地址:https://www.cnblogs.com/web-chuanfa/p/9162451.html
Copyright © 2020-2023  润新知