小项目中
小项目中不可能有太多状态需要vuex管理,在store.js中不需要做分类处理
const store = new Vuex.Store({
state: {},
mutations: {},
getter: {},
action: {}
})
export default store
在.vue文件中使用
import { mapGetter } form 'vuex'
...
computed: {
...mapGetter([''])
}
在.js文件中使用
import store form '@/store/store.js'
...
store.state.key
store.commit('mutation')
稍微大点的项目
在项目复杂点的项目中,可以按业务模块来划分,这样数据结构清晰,便于多人协作开发,这里贴上官方demo
此结构有根级状态的和模块状态,在 Vuex 模块化中,state 是唯一会根据组合时模块的别名来添加层级的,后面的 getters、mutations 以及 actions 都是直接合并在 store 下。如果不同模块中有同名的 mutation,Vuex 不会报错,通过 store.commit 调用,会依次触发所有同名 mutation。getters重民会报错,actions同mutation,state没有合并,不存在同名问题
目录结构
├── index.html
├── main.js
├── api
│ └── ... # 抽取出API请求
├── components
│ ├── App.vue
│ └── ...
└── store
├── index.js # 我们组装模块并导出 store 的地方
├── actions.js # 根级别的 action
├── mutations.js # 根级别的 mutation
└── modules
├── cart.js # 购物车模块
└── products.js # 产品模块
index.js
import Vue from 'vue'
import Vuex from 'vuex'
import actions from './actions.js'
import mutations from './mutations.js'
import cart from './modules/cart'
import products from './modules/products'
import createLogger from '../../../src/plugins/logger'
Vue.use(Vuex)
const debug = process.env.NODE_ENV !== 'production'
export default new Vuex.Store({
actions,
mutations,
// 每一个模块里的状态(state)都是独立的
modules: {
cart,
products
},
strict: debug,
// vuex自带的调试工具,主要检测我们对state的更改是不是通过mutations,开启时在控制台输出
plugins: debug ? [createLogger()] : []
})
cart.js
export default{
state:{
checked_goods:[]
},
mutations:{
updataCheckedGoods(state, new_goods){
state.checked_goods = [...state.checked_goods, ...new_goods]
}
}
}
products.js
// initial state
// 访问模块 cart 中的 state,要通过 store.state.cart.xxx,访问根 store 上申明的 state,依然是通过 store.state.xxx 直接访问。
const state = {
all: []
}
// actions
// action 的回调函数接收一个 context 上下文参数,context 包含:
// 1. state、2. rootState、3. getters、4. mutations、5. actions 五个属性,通过es6的解构赋值,看起来更优雅
const actions = {
getAllProducts ({ commit }) {
commit('setProducts', products)
// 前面说过,mutations会合并,所以ction 中可以通过 context.commit 跨模块调用 mutation,同时一个模块的 action 也可以调用其他模块的 action
commit('updataCheckedGoods', [])
}
}
// mutations
// mutation 的回调函数中接收的参数是当前模块的 state。
const mutations = {
setProducts (state, products) {
state.all = products
}
}
export default {
state,
actions,
mutations
}