vue3+ts vuex的使用
目录
vuex官方文档
1.安装
参考官网
2.store
初始化store
import { createStore } from 'vuex'
const store = createStore({})
export default store
main.ts引入store
import store from './store'
createApp(App).use(store)
3.state
初始化state
import { createStore} from 'vuex'
interface IUserInfo{
id: string,
account: string,
avatar: string,
nickname: string,
status: number
}
interface IState{
user:IUserInfo
}
const state:IState = {
user:{} as IUserInfo
}
const store = createStore({
state:state
})
export default store
使用state
import { useStore } from 'vuex'
const store = useStore()
store.state.userInfo
4.getters
getters就是在state上进行的封装
定义getters
//定义
const getters = {
getUserInfo(state?:IState){
return state?.user
}
}
//注册
const store = createStore({
state:state,
getters:getters
})
getters派生方法
getters可以对state里面的数据起到过滤的作用,比如返回角色是超级管理员的用户。
const getters = {
isAdmin:(state?:Istate)=>(id:number)=>{
return id === state?.admin.id
}
}
使用getters派生方法
const isAdmin = store.getters.isAdmin(2)
5.mutation
更改Vuex的store中的状态的唯一方法是提交mutation。接受state作为第一个参数。
初始化mutation
//定义mutation,注意此时如果不把state:IState作为第一个参数传入,会报类型不匹配的错误
const mutations = {
setUserInfo(state:IState,user:IUserInfo){
state.user = user
}
}
//注册到store里面
const store = createStore({
state:state,
getters:getters,
mutations:mutations
})
commit使用mutation中函数
import { useStore } from 'vuex'
const store = useStore()
const setUserInfo = () => {
store.commit('setUserInfo', {
id: 'idtest',
account: 'zhao',
avatar: 'avat',
nickname: 'xin',
status: 1
})
//打印验证是否修改state数据
console.log('store.state.user', store.state.user)
}
响应式渲染state中的数据
此时user信息虽然更改,但页面上不会做响应式变化,想要使用响应式变化,需要使用computed
const user = computed(() => store.state.user)
不这样定义也可以,在html代码中使用store进行渲染
<template>
{{store.state.user}}
</template>