mapState / mapMutations 的使用方法

Vue 引入 Vuex

// store/index.js
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const store = new Vuex.Store({
    // >>> 模块 >>>
    modules: {
        user: {
            state: {
                name: "sqrtcat",
                age: 29
            },
            mutations: {
                setUserName(state, userName) {
                    state.name = userName
                },
                setUserAge(state, userAge) {
                    state.age = userAge
                }
            }
        }
    },
    // <<< 模块 <<<
    state: {
        account: "",
        password: "",
        age: 0
    },
    mutations: {
        account(state, account) {
            state.account = account;
        },
        account(state, password) {
            state.password = password;
        },
        account(state, age) {
            state.age = age;
        },
    }
})

export default store

挂载至 Vue

import Vue from 'vue'
import App from './App'

import store from './store'

Vue.config.productionTip = false

Vue.prototype.$store = store

const app = new Vue({
    store,
    ...App
})
app.$mount()

页面引用 Vuex

使用 mapState, mapMutations 魔术方法导入

mapState

传递的是 this.$store.state 属性, 这样就可以省去 this.$store

// ....

mapMutations

传递的是 this.$store.commit 属性,这样就可以省去 this.$store

// ....

你可能感兴趣的:(vuex,vux)