vuex-persistedstate让vuex数据持久化

1.安装vuex-persistedstate

npm i vuex-persistedstate

2.在store/index.js中引入

import createPersistedState from "vuex-persistedstate"

3.使用vuex-persistedstate

import { createStore } from 'vuex'
import createPersistedState from "vuex-persistedstate"

export default createStore({
    state: {
        id: '',
        userAccount: '',
        userAvatar: '',
        userName: '',
        userRole: '',
        gender: '',
        phone: '',
    },
    mutations: {
        setUserAccount: (state, payload) => {
            state.userAccount = payload.value;
        },
        setId: (state,payload) => {
            state.id = payload.value
        },
        setUserAvatar: (state,payload) => {
            state.userAvatar = payload.value
        },
        setUserName: (state,payload) => {
            state.userName = payload.value
        },
        setUserRole: (state,payload) => {
            state.userRole = payload.value
        },
        setGender: (state,payload) =>{
            state.gender = payload.value
        },
        setPhone: (state,payload) =>{
            state.phone = payload.value
        },

    },
    actions: {
    },
    modules: {
    },
    plugins:[createPersistedState({
        storage: window.sessionStorage,
        reducer(val){
            return{
                id: val.id,
                userAccount: val.userAccount,
                userAvatar: val.userAvatar,
                userName: val.userName,
                userRole: val.userRole,
                gender: val.gender,
                phone: val.phone,
            }
        }
    })]
})

4.获取值

const store = useStore()
state.userName = store.state.userName
state.userAccount = store.state.userAccount
state.userAvatar = store.state.userAvatar
state.userId = store.state.id
state.userPhone = store.state.phone

5.修改值

 const store = useStore();
 store.commit("setUserAccount",{value: state.user.userAccount})
 store.commit("setId",{value: state.user.id})
 store.commit("setUserName",{value: state.user.userName})
 store.commit("setUserAvatar",{value: state.user.userAvatar})
 store.commit("setUserRole",{value: state.user.userRole})
 store.commit("setPhone",{value: state.user.phone})

你可能感兴趣的:(前端,javascript,开发语言)