1. Vuex的五个核心概念:state、getters、mutations、actions、modules。
2. 名词解释:
- state:状态数据(各种数据变量)
- getters:对状态数据经过一些处理后,生成的数据(变量)
- mutations:同步方法,可用来修改state值。注:方法名常一律都用大写字母表示, 如:SET_NAME(state, payLoad) {...}
- actions: 异步方法,如通过ajax异步请求后端获取一些数据,然后交给mutations去修改state。
- modules: 模块化vuex,每一个模块都拥有自己独立的 state、mutation、action、 getters,使得结构非常清晰,方便管理。注:调用时,常用斜杠/符号, 如:模块名/xxx
安装vuex库: npm i vuex
store/modules/app.js文件
import Cookies from 'js-cookie'
const state = {sidebar: {opened: Cookies.get('sidebarStatus') ? !!+Cookies.get('sidebarStatus') : true,withoutAnimation: false},device: 'desktop',
}const mutations = {OPEN_SIDEBAR: (state) => {Cookies.set('sidebarStatus', 1)state.sidebar.opened = true},CLOSE_SIDEBAR: (state, withoutAnimation) => {Cookies.set('sidebarStatus', 0)state.sidebar.opened = falsestate.sidebar.withoutAnimation = withoutAnimation},TOGGLE_DEVICE: (state, device) => {state.device = device},
}const actions = {closeSideBar({ commit }, { withoutAnimation }) {commit('CLOSE_SIDEBAR', withoutAnimation)},toggleDevice({ commit }, device) {commit('TOGGLE_DEVICE', device)},
}export default {namespaced: true, // 模块化state,mutations,actions
}
store/getters.js文件
// 把不同模块的都汇总
const getters = {sidebar: state => state.app.sidebar, // app模块device: state => state.app.device,token: state => state.user.token, // user模块avatar: state => state.user.avatar,name: state => state.user.name,introduction: state => state.user.introduction,
}
export default getters
store/index.js文件
import Vue from 'vue'
import Vuex from 'vuex'
import getters from './getters'Vue.use(Vuex)// 将不同模块的状态管理汇总
// https://webpack.js.org/guides/dependency-management/#requirecontext
const modulesFiles = require.context('./modules', true, /\.js$/)// you do not need `import app from './modules/app'`
// it will auto require all vuex module from modules file
const modules = modulesFiles.keys().reduce((modules, modulePath) => {// set './app.js' => 'app'const moduleName = modulePath.replace(/^\.\/(.*)\.\w+$/, '$1')const value = modulesFiles(modulePath)modules[moduleName] = value.defaultreturn modules
}, {})const store = new Vuex.Store({modules,getters
})export default store
工具库:js-cookie、
1. 状态管理:分模块和不分模块,分模块需要使用斜杠/符号来标志(模块名/xxx)。
2. 使用方式(2种):
方式1: 使用vuex库内置的4个mapXX函数,来解构vuex对象
方式2: 使用this.$store.xxx方式(即:将store注册到vue的)。
某个模块的getter数据:{{ $store.gerters.模块名.数据项名 }}state数据:{{ this.$store.state.count }}使用计算属性:{{ sidebar }}{{ showSettings }}
参考链接: