Vuex的辅助函数mapState, mapActions, mapGetters,mapMutations用法代码例子

Vuex的辅助函数mapState, mapActions, mapGetters,mapMutations用法代码例子

    • 参考资料
    • 调用函数的文件
    • store/index.js文件
    • store/getter.js
    • store/modules/car.js
    • store/modules/person.js

参考资料

  1. https://www.cnblogs.com/tugenhua0707/p/9794423.html
    2.https://vuex.vuejs.org/zh/api/#组件绑定的辅助函数

调用函数的文件








store/index.js文件

import Vue from 'vue'
import Vuex from 'vuex'

import person from './modules/person'
import car from './modules/car'
import getters from './getters'


Vue.use(Vuex)
console.log("vuex插件已完成安装")

export default new Vuex.Store({

    modules: {
        person,
        car
    },
    state: {

    },
    mutations: {

    },
    actions: {

    },
    getters
})

store/getter.js

const getters = {
    num: state => state.person.num,
    type: state => state.person.type,
    from: state => state.person.from,
    name: state => state.car.name,
    age: state => state.car.age
}
export default getters

store/modules/car.js



const car = {

    state: {
        name: 'zxy',
        age: 12,

    },
    mutations: {
        getMyInfo(state) {
            for (let key in state) {
                console.log(key)
            }
        }
    },
    actions: {
        getMyInfo2({ commit }) {
            return new Promise((resolve, reject) => {
                setTimeout(() => {
                    commit('getMyInfo')
                }, 1000)
            })
        }
    }

}

export default car;

store/modules/person.js

import { reject } from "q";


const person = {

    state: {
        num: 10,
        type: "轿车",
        from: "china",
    },
    mutations: {
        getMyInfo(state) {
            for (let key in state) {
                console.log(key)
            }
        }
    },
    actions: {
        getMyInfo2({ commit }) {
            return new Promise((resolve, reject) => {
                setTimeout(() => {
                    commit('getMyInfo')
                    resolve()
                }, 1000)
            })

        }
    }

}

export default person;

你可能感兴趣的:(vue2js,Vuex辅助函数)