相信大部分人都知道vuex的基礎用法。無非是
export default new Vuex.Store({ state: { //這裡定義自己需要的屬性。 token:'', user:{ name:'david' } }, mutations: { setUser: (state, userinfo) => { state.user = userinfo } }, actions: { saveUser ({ commit }, data) { return new Promise(resolve => { commit('setUser', data) resolve() }) } },})這種應該是最常規的用法
模組化也很簡單,index.js看起來是這樣的
import Vue from 'vue'import Vuex from 'vuex'import app from './modules/app'import user from './modules/user'import getters from './getters'Vue.use(Vuex)export default new Vuex.Store({ modules: { app, user, permission }, state: { }, mutations: { }, actions: { }, getters})
然後user.js裡面程式碼是這種
import Vue from 'vue'const user = { userInfo: { name:'', gender: 1 }, mutations: { SET_USER: (state, user) => { state.userInfo = user }, }, actions: { saveUser ({ commit }, user) { commit('SET_USER', user) }, // 登出 Logout ({ commit, state }) { return new Promise((resolve) => { logout(state.token).then(() => { resolve() }).catch(() => { resolve() }).finally(() => { commit('SET_TOKEN', '') }) }) } }}export default user
這樣就一個最簡單的模組化了便實現好了
我的習慣是把getter單獨抽取出來作為一個module
例如我的getter.js如下
const getters = { nickname: state => state.user.name, userInfo: state => state.user.userInfo,}export default getters
使用也很簡單
在需要用到的地方首先引入進來
import { mapActions, mapGetters } from 'vuex'
userInfo這種適合用computed屬性來引入,這樣可以實時的檢測到這個屬性的更新
computed: { ...mapGetters(['nickname', 'avatar'])},methods: { ...mapActions(['Logout']),}
最新評論