Open
Description
前言
vuex想必不需要我介绍很多了,这一节主要是为了填补项目没有引入vuex的问题,之后做完脚手架可以选择是否使用vuex。
因为vuex用的实在是很普遍,就不介绍细节了,我们直接搭项目。
新建文件
在app
目录新建文件夹store
:
app/store
├── README.md
├── actions.js
├── getters.js
├── index.js
├── mutation-types.js
├── mutations.js
└── state.js
上代码
不多说,直接上代码吧。
actions.js
:
import * as types from './mutation-types'
/* 增加年龄 */
export const ageIncrease = function ({commit}) {
setTimeout(() => {
commit(types.AGE_INCREASE)
}, 3000)
}
getters.js
:
// 获取名字
export const name = state => state.name
index.js
:
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'
import createLogger 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 ? [createLogger()] : []
})
mutation-types.js
:
export const AGE_INCREASE = 'AGE_INCREASE'
mutations.js
:
import * as types from './mutation-types'
const mutations = {
/* 增加年龄 */
[types.AGE_INCREASE](state) {
state.age ++
}
}
export default mutations
state.js
:
const state = {
name: '子咻',
age: 18
}
export default state
最后我们将vuex引入app
下的index.js
就好了。
如果项目非常大,还需要module来管理的话,可以按照当前规则,进行改造即可。
说明
- 所有的state获取,都用getters封装后使用,这样就很容易知道get了哪些数据,让项目一目了然
- mutations竟可能干净,一个mutation中的代码尽可能只写一行
以上两点会让代码更清晰
最后
到现在,我们就将整个项目的骨架搭好了,下一章,我们将正式开始做脚手架。