Data Persistence: An Implementation Approach in Vue Vuex
When using Vuex for state management in Vue, you can use localStorage to store and retrieve data if you need to persist some data. Here is an example:
First, create a storage.js file in the src/utils folder to encapsulate the operation of localStorage:
// 约定一个通用的键名
const INFO_KEY = 'hm_shopping_info'
// 获取个人信息
export const getInfo = () => {
const defaultObj = { token: '', userId: '' }
const result = localStorage.getItem(INFO_KEY)
return result ? JSON.parse(result) : defaultObj
}
// 设置个人信息
export const setInfo = (obj) => {
localStorage.setItem(INFO_KEY, JSON.stringify(obj))
}
// 移除个人信息
export const removeInfo = () => {
localStorage.removeItem(INFO_KEY)
}Then, import and call these methods in the JavaScript file in the store:
import { getInfo, setInfo } from '@/utils/storage'
// 通过getInfo方法获取持久化的个人信息
const info = getInfo()
// 在需要的地方使用setInfo方法进行持久化存储
setInfo({ token: 'xxxx', userId: 'xxxx' })By calling the getInfo method, the previously stored personal information can be obtained. By calling the setInfo method, the new personal information can be persisted.
Please note that this is just a simple example, and you can modify and extend it to suit your needs.
Disclaimers:The materials on this website are collected and sorted from the Internet. The copyright of the works belongs to the author. If it infringes your copyright, please send an email to us

简体中文
English
Article comments