Mutation
The only way to change the state in Vuex’s store is to commit mutation. Mutations in Vuex are very similar to events: each mutation has a string of event type (type)** and a ** callback function (handler). This callback is where we actually make the state change, and it takes state as the first argument:
import { createStore } from 'vuex'
interface IAdmin {
id: number
adminName: string
}
export interface IState {
admin: IAdmin
}
const state: IState = {
admin: { adminName: "yuemaedu".id: 1 } as IAdmin
}
const getters = {
getAdmin(state? : IState) {
returnstate? .admin },isAdmin: (state? : IState) = > (id: number) = > {
returnid === state? .admin.id } }const mutations = {
login(state: IState, admin: IAdmin) {
state.admin = admin
}
}
const store = createStore({
state: state,
getters: getters,
mutations: mutations
})
export default store
Copy the code
Definition of mutations
This callback is where we actually make the state change, and it accepts state as the first argument
const mutations = {
login(state: IState, admin: IAdmin) {
state.admin = admin
}
}
Copy the code
registered
const store = createStore({
state: state,
getters: getters,
mutations: mutations
})
Copy the code
use
Commit to submit
const login = () = > {
store.commit('login', { adminName: 'Jump Code Education'.id: 1})}Copy the code
Vuex responsive
<template>
{{ store.state.admin }}
{{ admin }}
{{ getAdmin }}
{{ isAdmin }}
<a-button type="primary" @click="login"</a-button> </template><script lang="ts">
import { computed, defineComponent } from 'vue'
import { useStore } from 'vuex';
import { IState } from '.. /.. /store';
export default defineComponent({
setup() {
const store = useStore<IState>()
const admin = computed(() = > store.state.admin)
const getAdmin = computed(() = > store.getters.getAdmin)
const isAdmin = computed(() = > store.getters.isAdmin(1))
const login = () = > {
store.commit('login', { adminName: 'Jump Code Education'.id: 1})}return {
store,
admin,
getAdmin,
isAdmin,
login
}
},
})
</script>
Copy the code
computed
const admin = computed(() = > store.state.admin)
const getAdmin = computed(() = > store.getters.getAdmin)
const isAdmin = computed(() = > store.getters.isAdmin(1))
return {
admin,
getAdmin,
isAdmin,
login
}
Copy the code
Use store directly in the template
{{ store.state.admin }}
const store = useStore<IState>()
return {
store,
}
Copy the code