1. state.js,存放的是状态
const state = {
// 数据存放
singer: null
}
export default state
2. mutation-types.js,定义mutation的常量
export const SET_SINGER = 'SET_SINGER'
3. mutations,改变state状态,只能通过mutations来改变state,这里是同步执行
import * as types from './mutation-types'
const mutations = {
// 第一个参数是状态state,第二个参数是组件传来的数据
[types.SET_SINGER] (state, singer) {
state.singer = singer
}
}
export default mutations
4. actions.js 异步
5. index.js 导出
import Vue from 'vue'
import Vuex from 'vuex'
import state from './state'
import mutations from './mutations'
import * as getters from './getters'
import actions from './actions'
// 控制台可以打印出state状态变化的前后值,便于跟踪状态变化
import createLogger from 'vuex/dist/logger'
Vue.use(Vuex)
// 通过debug开启strict严格模式,自动检测vuex操作是否正确
const debug = process.env.NODE_ENV !== 'production'
export default new Vuex.Store({
state,
actions,
mutations,
getters,
strict: debug,
plugins: debug ? [createLogger()] : []
}
)