zoukankan      html  css  js  c++  java
  • vuex(三)actions

    actions:既然mutations只能处理同步函数,我大js全靠‘异步回调’吃饭,怎么能没有异步,于是actions出现了...  
    actions和mutations的区别
        1.Actions 提交的是 mutations,而不是直接变更状态。也就是说,actions会通过mutations,让mutations帮他提交数据的变更。
        2.Action 可以包含任意异步操作。ajax、setTimeout、setInterval不在话下
    两秒后年龄增加
    看这样一段代码,大家就会明白他的使用:
    import Vue from 'vue'
    import Vuex from 'vuex'
     
    Vue.use(Vuex);
     
    const store = new Vuex.Store({
    state: {
        age: 18,
    },
    mutations: {
        add: function (state,value) {
            state.age += value;
        }
    },
    getters: {
        age: function (state) {
            return state.age;
        }
    },
    actions: {
        addAsync: function (context,value) {
            setTimeout(function(){
                context.commit('add',value);
            },2000)
        }
    }
    });
    export default store
     
    上述代码中mutations先定义一个方法add方法,然后再actions中异步操作,调用mutations中的方法,间接操作state中的数据。
    <template>
     
        <div @click="add" class="age">+{{age}}</div>
     
    </template>
    <script>
    import store from '../../../utils/store';
    export default {
    components: {
    },
    data () {
        return {
        }
    },
    computed: {
        age: function () {
            return store.getters.age;
        }
    },
    methods: {
        add: function () {
            store.dispatch('addAsync',5)
        }
    },
    }
    </script>
    <style scoped>
    .age {
     100rpx;
    height: 90rpx;
    line-height: 90rpx;
    border: 1rpx solid #ccc;
    }
    </style>
    上述代码中computed中的add为获取vuex中的数据,然后再methods中异步增加年龄。
     
  • 相关阅读:
    Light oj 1197
    UVA 11426 GCD
    Light oj 1236
    Light oj 1138
    Light oj 1214-Large Division (同余定理)
    Light oj 1234
    HDU
    ZOJ 3469 Food Delivery(* 区间DP 总结)
    二分查找整理
    zoj 3965 Binary Tree Restoring(* dfs)
  • 原文地址:https://www.cnblogs.com/bgwhite/p/9472348.html
Copyright © 2011-2022 走看看