vuex语法精简(方便开发查阅)

vuex语法精简(方便开发查阅)

本文只是方便开发的时候快速查阅到相关语法,想看详细内容请看官网(时间久了写法都忘了,~~哭)

store结构

store.vue
    import Vue from 'vue'
    import Vuex from 'vuex'

    Vue.use(Vuex)

    export default new Vuex.Store({
        state: {

        },
        getters: {

        },
        mutations: {

        },
        actions: {

        }
    })

main.js
    import store from './store'
    new Vue({
        store,
        render: h => h(App)
    }).$mount('#app')

state

store中state存储属性
    state: {
        count: 1
    },

获取store中的state属性
    computed: {
        count () {
            return this.$store.state.count
        }
    }

使用mapState获取state属性
    import { mapState } from 'vuex'
    方式一:
        computed: mapState({
            count1: state => state.count,
            count2: 'count',
            count3: state => state.count+1
        })
    方式二:
        computed: {
            ...mapState({count:'count'})
        }
    方式三:
        computed: {
            ...mapState(['count'])
        }

Getter

store中getters存储属性
    getters: {
        filtercount: state => state.count < 0 ? 0: state.count
    },

获取store中的getters属性
    this.$store.getters.filtercount

使用mapGetters获取getters属性(用法和mapState一样)

Mutation

store中mutations存储修改属性的方法
    mutations: {
        increment(state, param) {
            state.count+=param.data
        }
    },

触发mutations
    方式一
        this.$store.commit("increment", {
            data: 10
        });

    方式二
        this.$store.commit({
            type: 'increment',
            data: 10
        });

actions

store中actions存储提交mutations的方法
    actions: {
        incrementAsync({ commit }, param) {
            commit({
                type: 'increment',
                data: param.data
            });
        }
    }

触发actions
    this.$store.dispatch({
        type: 'incrementAsync',
        data: 10
    })

使用mapActions获取actions方法(用法和mapState一样)
    methods: {
        ...mapActions([ 'increment'])
    }

猜你喜欢

转载自www.cnblogs.com/ye-hcj/p/10365372.html