Skip to content

从零开始做Vue前端架构(8)vuex #17

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
CodeLittlePrince opened this issue May 15, 2018 · 0 comments
Open

从零开始做Vue前端架构(8)vuex #17

CodeLittlePrince opened this issue May 15, 2018 · 0 comments

Comments

@CodeLittlePrince
Copy link
Owner

前言

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来管理的话,可以按照当前规则,进行改造即可。

说明

  1. 所有的state获取,都用getters封装后使用,这样就很容易知道get了哪些数据,让项目一目了然
  2. mutations竟可能干净,一个mutation中的代码尽可能只写一行
    以上两点会让代码更清晰

最后

到现在,我们就将整个项目的骨架搭好了,下一章,我们将正式开始做脚手架。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant