1.目錄結構vue
2.開始(安裝vuex)vuex
npm install vuex --savenpm
3.編輯store/index.js(建立一個Vuex.store狀態管理對象)ide
import Vue from 'vue' import Vuex from 'vuex' import * as actions from './actions' import * as getters from './getters' import state from './state' import mutations from './mutations' //開發的時候藉助這個咱們能夠在控制檯追蹤到state更改的各個狀態 import creatLogger from 'vuex/dist/logger' Vue.use(Vuex) const debug = process.env.NODE_ENV !== 'production' export default new Vuex.Store({ actions, getters, state, mutations, strict: debug, plugins: debug ? [creatLogger()] : [] })
4.編輯store/state.js(也就是添加你要管理的數據)this
const state = { showSignModel: false, currentday: 0, chooseClaState: false, signState: false, awardInfo: {} } export default state
5.編輯store/mtations-types.js(這個主要是爲了組織代碼的時候足夠清晰,便於維護,在mutation.js中幫助咱們創建映射關係)spa
const SET_SHOW_SIGN_MODEL = 'SET_SHOW_SIGN_MODEL' const SET_CURRENT_DAY = 'SET_CURRENT_DAY' const SET_CHOOSE_CLASS = 'SET_CHOOSE_CLASS' const SET_SIGN_STATE = 'SET_SIGN_STATE' const SET_AWARD_INFO = 'SET_AWARD_INFO' export { SET_SHOW_SIGN_MODEL, SET_CURRENT_DAY, SET_CHOOSE_CLASS, SET_SIGN_STATE, SET_AWARD_INFO }
6.編輯store/mutation.js(在vuex中要修改state的的狀態或者說值,只能經過mutation去修改,mutation是同步的)debug
import * as types from './mutation-types' const mutations = { [types.SET_SHOW_SIGN_MODEL] (state, showSignModel) { state.showSignModel = showSignModel }, [types.SET_CURRENT_DAY] (state, currentday) { state.currentday = currentday }, [types.SET_CHOOSE_CLASS] (state, chooseState) { state.chooseClaState = chooseState }, [types.SET_SIGN_STATE] (state, signState) { state.signState = signState }, [types.SET_AWARD_INFO] (state, info) { state.awardInfo = info } } export default mutations
7.編輯store/getters.js(經過getters.js咱們能夠獲取state中的狀態)code
const showSignModel = state => state.showSignModel const currentday = state => state.currentday const chooseClaState = state => state.chooseClaState const signState = state => state.signState const awardInfo = state => state.awardInfo export { showSignModel, currentday, chooseClaState, signState, awardInfo }
8.若是要同時修改多個狀態時,這個時候咱們能夠將多個mutation封裝爲一個actions(actions能夠一次性提交多個mutation)對象
import * as types from './mutation-types' const setSignState = function ({commit, state}, {info, signState}) { commit(types.SET_AWARD_INFO, info) commit(types.SET_SIGN_STATE, signState) } export { setSignState }
9.在組件中獲取狀態(在computed獲取)blog
先引入vuex給咱們提供的語法糖 import { mapGetters} from 'vuex' computed: { ...mapGetters([ 'signState', 'awardInfo' ]) } 根據狀態顯示元素 <div class="sign_model" v-show="signState"></div>
10.在組件中修改狀態(要記得將vuex提供給咱們的依法堂書寫在methods下,以下:)
先引入vuex給咱們提供的語法糖 import { mapMutations } from 'vuex' methods: { closeMode () { // 關閉彈窗 setTimeout(() => { this.hideMode(false) }, 2500) }, ...mapMutations({ hideMode: 'SET_SIGN_STATE' }) }
先引入vuex給咱們提供的語法糖 import { mapActions } from 'vuex' 一樣也要寫在methods下 methods: { test () { this.setSignState({ info: obj, testState: false }) }, ...mapActions([ 'setSignState' ]) }