首先在项目中新建utils文件夹,再创建storage.js文件,这个文件就是封装本地存储的页面

storage.js

// 本地存储模块
// 获取
export const getItem=(name,value)=>{
    // 未经处理的请求数据
    const data=window.localStorage.getItem(name)  
    try {
        // 将data转为js对象
      return JSON.parse(data)
    } catch (error) {
      return data  
    }
  
}
// 存储
export const setItem=(name,value)=>{
    // 如果value是对象,把value转为json字符串存储
    if (typeof value==='object') {
        value=JSON.stringify(value)
    }
    window.localStorage.setItem(name,value)
}
// 删除
export const removeItem=name=>{
    window.localStorage.removeItem(name)
}

在vuex中引入模块

import Vue from 'vue'
import Vuex from 'vuex'
//引入模块
import {getItem,setItem} from '@/utils/storage'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
  //使用模块中的方法
    user:getItem('user')

    // 用户登录状态
    // user:JSON.parse(window.localStorage.getItem('user'))
  },
  mutations: {
    // 修改
    setuser(state,data){
      state.user=data
      setItem('user',state.user)
      // window.localStorage.setItem('user',JSON.stringify(state.user))
    }
  },
  actions: {
  },
  modules: {
  }
})

在页面中存储信息

 this.$store.commit('setuser',this.user)
Logo

欢迎加入 MCP 技术社区!与志同道合者携手前行,一同解锁 MCP 技术的无限可能!

更多推荐