Vuex是项目中数据共享的重要组成部分,本文章总结个人在项目中使用Vuex的使用方法。
- 设置项目目录src/store
在这将actions,getters,mutations,state,单独抽象成一个文件进行管理。为了使mutation看起来更加简洁明了,将mutation-types也分割出来统一管理。
├── store
├── index.js # 我们组装模块并导出 store 的地方
├── state.js # 根级别的 states
├── getters.js # 根级别的 getters
├── actions.js # 根级别的 action
├── mutations.js # 根级别的 mutation
└── mutation-types.js # mutation类型
- index.js
import Vue from 'vue'
import Vuex from 'vuex'
import * as mutations from './mutations'
import * as actions from './actions'
import state from './state'
import createLooger from 'vuex/dist/logger' // 在没有装vue-devtools的情况下可以使用,在控制台会打印出state前后状态变化
Vue.use(Vuex)
const debug = process.env.NODE_ENV === 'production'
export default new Vuex.store({
state,
mutations,
actions,
getters,
strict: debug, // 开发环境下开启严格模式,任何不是由mutation引起更改state的操作都会抛出错误,确保在发布环境下关闭严格模式,以避免性能损失。
plungins: debug ? [createLogger()] : [] // 开发环境下开启
})
- state.js
设置全局共享的数据,举个例子如下:
export default state = {
userName: '',
stationList: [],
station: {}
}
- getters.js
Vuex允许在store中定义getter,可以认为是store的计算属性。当值改变时也会重新计算。
getter接收state作为其第一个参数。
export const userName = state => state.userName
export const stationList = state => state.stationList
export const station = state => state.station
由于Vuex的状态存储是响应式的,因此在使用数据时可以利用计算属性从store实例中读取数据。
import { mapGetters } from 'vuex
computed: {
...mapGetters([
name: 'userName',
'stationList',
'station'
])
}
- actions.js
Action用于提交Mutation,而不直接修改状态。
import * as types from './mutation-types'
export const selectStation = function({ commit, state }, param) {
if(state.stationList.length === 0) {
commit(types.SELECT_STATION, param)
}
}
使用Action时需要从methods中使用。
import { mapActions } from 'vuex'
methods: {
...mapActions([
'selectStation'
]),
_changeStation(station) {
this.selectStation(station)
}
}
- mutations.js
import * as types from './mutation-types'
export mutations = {
[types.SELECT_STATION](state, param) {
state.station = param
}
}
- mutation-types.js
使用常量替代 mutation 事件类型在各种 Flux 实现中是很常见的模式。这样可以使 linter 之类的工具发挥作用,同时把这些常量放在单独的文件中可以让你的代码合作者对整个 app 包含的 mutation 一目了然:
export const SELECT_STATION = 'SELECT_STATION'
https://github.com/Gesj-yean/vue-demo-collection 记录了更多优秀插件的使用方法。有时间的同学请看我的置顶博客,可太感谢啦。