1.安装
npm安装
npm install vuex@next --save
yarn安装
yarn add vuex@next --save
2.基本结构
import Vuex from 'vuex'
const store = createStore({
state() {
return {
name: 0,
code:"",
todos: [
{ id: 1, text: '...', done: true },
{ id: 2, text: '...', done: false }
]
}
},
getters: {
doneTodos (state) {
return state.todos.filter(todo => todo.done)
}
},
mutations: {
saveName(state,name){
state.name= name;
},
saveCode(state,code){
state.code= code;
},
},
actions: {
increment (context) {
context.commit('increment')
}
},
})
export default store
3.多模块的结构
import Vuex from 'vuex'
const module1 = {
namespaced: true,
state: () => ({ ... }),
mutations: { ... },
actions: { ... },
getters: { ... }
}
const module2 = {
namespaced: true,
state: () => ({ ... }),
mutations: { ... },
actions: { ... },
getters: { ... }
}
const module3 = {
namespaced: true,
state: () => ({ ... }),
mutations: { ... },
actions: { ... },
getters: { ... }
}
const store = createStore({
modules: {
module1: module1,
module2: module2,
module3: module3,
}
})
export default store
main.js 注册store
import store from 'path';
new Vue({
el: '#app',
store,
render: h => h(App)
});
4.使用方法
1.获取状态
this.$store.state.状态名
this.$store.state.模块名.状态名
computed:{
...mapState({
'状态名1',
'状态名2',
...
})
}
computed:{
...mapState({
module1: state => state.some.nested.module.module1,
module2: state => state.some.nested.module.module2
})
}
2.调用getter
this.$store.getters.doneTodosCount
computed: {
...mapGetters([
'doneTodosCount',
'anotherGetter',
])
}
3. 调用mutations
this.$store.commit('mutations的方法名')
this.$store.commit('mutations的方法名',parmas)
this.$store.commit('模块名/调用模块的mutations的方法名',parmas)
methods: {
...mapMutations([
'increment',
'incrementBy'
]),
}
4.调用Action
methods: {
...mapActions([
'increment',
'incrementBy'
]),
...mapActions({
add: 'increment'
})
}