vuex之mutations-getters-actions異步(四)

1、mutations(修改狀態)

(1)template中直接使用$store.commit( )觸發

// template<button @click="$store.commit('ADD')">+</button>// src/vuex/store.jsconst mutations = {
    // 狀態變更函數
    ADD (state) {
        state.count++;
    }}

(2)利用mapMutations引入觸發

<template>
    <div class="hello">
        <h1>{{ msg }}</h1>
        <h2>{{count}}</h2>
        <!-- 3、、直接調用相應的方法 -->
        <button @click="ADD">+</button>
    </div></template><script>// 1、引入mapMutationsimport {mapState, mapMutations} from 'vuex'export default {
    data () {
        return {
            msg: 'Vuex test!'
        }
    },
    // 通過mapState的JSON來賦值
    computed: mapState({
        count: 'count'
    }),
    // 2、methods中加入mapMutations
    methods: mapMutations([
        'ADD'
    ])}</script><style scoped></style>

2、getters(獲取state和過濾)

(1)基本用法

// src/vuex/store.jsconst getters = {
    count: function(state){
        // 返回加上100
        return state.count + 100;
    }}

(2)常規獲取值

computed: {
    // 獲取getters
    count(){
        return this.$store.getters.count;
    }}

(3)mapGetters獲取值

// 1、引入mapMutationsimport {mapState, mapMutations, mapGetters} from 'vuex'// 2、使用computed: {
    // 獲取getters
    ...mapGetters(["count"])}

3、actions(異步狀態修改)

actions和mutations功能基本一樣,不同點是,actions是異步的改變state狀態,而mutations是同步改變狀態。不過實際項目中一般都是通過actions改變mutations中的值。
(1)store.js中增加異步代碼

// src/vuex/store.jsconst actions ={
    // 觸發mutations中相應的方法
    add ({commit}) {
        // 增加異步
        setTimeout(()=>{
            commit('ADD')
        },3000);
        console.log('我比reduce提前執行');
    }}

(2)常規使用

// template<button @click="add">+</button>// scriptmethods: {
    add() {
        //分發action
        this.$store.dispatch('add');
    }}

(3)mapActions的使用

// template<button @click="add">+</button>// script// 引入mapActionsimport {mapState, mapActions} from 'vuex'// 使用mapActionsmethods: {
    ...mapActions(['add'])}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章