安装VUEX npm i vuex -save
通常代码放在src/store目录下
第一步:创建以下JS文件
src/store/index.js
src/store/actions.js
src/store/getters.js
src/store/mutation-types.js
src/store/mutations.js
src/store/state.js
第二步:定义state
state.js
const state = {
singer: {}
}
export default state
第三步:定义mutation-types
设置一些常量
通常mutation都有mutation-types做关联
mutation-types.js
export const SET_SINGER = 'SET_SINGER'
第三步:在mutations中定义修改的操作
引入mutation-types,拿到常量的types
定义matutaions,放一些mutation相关的修改方法
传入的第一个参数是当前状态树的state,第二个参数是提交mutation传入的参数
mutations.js
import * as types from './mutation-types'
const matutaions = {
[types.SET_SINGER](state, singer) {
state.singer = singer
}
}
export default matutaions
第四步:从getters中获取数据到组件中
getters.js
export const singer = state => state.singer
第五步:index入口JS初始化
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()] : []
})
第六步:注入Store
main.js
import store from './store'
new Vue({
el: '#app',
store,
router,
render: h => h(App)
})
vuex的初始化及配置基本搞定!
第七步:set数据,修改state
使用vuex默认提供的语法糖
import {mapMutations} from 'vuex'
//在methods中,做对象映射,把mutation的修改映射成为一个方法名,对应的是mutation-types中的常量
...mapMutations({
setSinger: 'SET_SINGER'
})
//调用方法,传入数据,实现mutation的提交
this.setSinger(singer)
第七步:get数据
使用vuex默认提供的语法糖
import {mapGetters} from 'vuex'
computed: {
...mapGetters([
'singer'
])
},
created() {
console.log(this.singer)
}
*未使用到异步action方法,后续整理