const store = new Vuex.Store({
state: {
count: 0
}
})
this.$store.state.count
import { mapState } from 'vuex'
computed: {
...mapState(['count']),
...mapState({
countAlias: 'count',
countPlusLocalState(state) {
return state.count + this.localCount
}
})
}
const store = new Vuex.Store({
state: {
todos: [
{ id: 1, text: '...', done: true },
{ id: 2, text: '...', done: false }
]
},
getters: {
doneTodos: state => {
return state.todos.filter(todo => todo.done)
},
doneTodosCount: (state, getters) => {
return getters.doneTodos.length
},
getTodoById: (state) => (id) => {
return state.todos.find(todo => todo.id === id)
}
}
})
this.$store.getters.doneTodos
this.$store.getters.getTodoById(2)
import { mapGetters } from 'vuex'
computed: {
...mapGetters(['doneTodosCount']),
...mapGetters({
doneCount: 'doneTodosCount'
})
}
const store = new Vuex.Store({
state: {
count: 1
},
mutations: {
increment(state) {
state.count++
},
incrementBy(state, payload) {
state.count += payload.amount
}
}
})
this.$store.commit('increment')
this.$store.commit('incrementBy', { amount: 10 })
import { mapMutations } from 'vuex'
methods: {
...mapMutations(['increment']),
...mapMutations({
add: 'increment'
})
}
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment(state) {
state.count++
}
},
actions: {
increment(context) {
context.commit('increment')
},
incrementAsync({ commit }) {
setTimeout(() => {
commit('increment')
}, 1000)
},
async actionA({ commit }) {
const data = await fetch('/api/data')
commit('setData', data)
}
}
})
this.$store.dispatch('increment')
this.$store.dispatch('incrementAsync')
import { mapActions } from 'vuex'
methods: {
...mapActions(['increment']),
...mapActions({
add: 'increment'
})
}
const moduleA = {
namespaced: true,
state: () => ({ count: 0 }),
mutations: {
increment(state) {
state.count++
}
},
actions: {
incrementIfOdd({ state, commit }) {
if (state.count % 2 === 1) {
commit('increment')
}
}
},
getters: {
doubleCount(state) {
return state.count * 2
}
}
}
const store = new Vuex.Store({
modules: {
a: moduleA
}
})
this.$store.state.a.count
this.$store.getters['a/doubleCount']
this.$store.commit('a/increment')
this.$store.dispatch('a/incrementIfOdd')
store/
├── index.js # 组装模块并导出 store
├── actions.js # 根级别的 action
├── mutations.js # 根级别的 mutation
└── modules/
├── user.js # 用户模块
└── cart.js # 购物车模块
import Vue from 'vue'
import Vuex from 'vuex'
import user from './modules/user'
import cart from './modules/cart'
Vue.use(Vuex)
export default new Vuex.Store({
modules: {
user,
cart
}
})
export default {
namespaced: true,
state: {
userInfo: null
},
mutations: {
SET_USER_INFO(state, userInfo) {
state.userInfo = userInfo
}
},
actions: {
async getUserInfo({ commit }) {
const res = await fetch('/api/user')
commit('SET_USER_INFO', res.data)
}
},
getters: {
userName: state => state.userInfo?.name
}
}