In the WeChat applet, local storage can be used to save some data such as user status, name, gender, etc.;
Local storage mainly includes two methods: cache and local data storage.
- cache
Cache is a temporary storage mechanism for fast access to memory, which can effectively improve the response speed of applications. In the WeChat applet, you can use
wx.setStorage
methods andwx.getStorage
methods to implement data caching. For example:
// 设置缓存数据
wx.setStorage({
key: 'userInfo',
data: { name: 'Tom', age: 20 },
success: function () {
console.log('设置缓存数据成功');
}
});
// 获取缓存数据
wx.getStorage({
key: 'userInfo',
success: function (res) {
console.log(res.data);
}
});
In the above example, a named cache data
wx.setStorage
is set through the method , and the content is an object . The cached data is obtained through the method, and the cached data is output in the console after the acquisition is successful.userInfo
{name: 'Tom', age: 20}
wx.getStorage
The size of the cached data is generally limited by the memory of the device. Some low-end devices may experience unstable cached data and even cause problems such as application crashes.
2. Local data storage
Local data storage refers to storing data in the local file system of the device, which can maintain data persistence. In WeChat applets, local storage of data can be realized using
wx.setStorageSync
methods and methods.wx.getStorageSync
For example:
// 设置本地存储数据
wx.setStorageSync('userInfo', { name: 'Tom', age: 20 });
// 获取本地存储数据
var userInfo = wx.getStorageSync('userInfo');
console.log(userInfo);
In the above example, wx.setStorageSync
a named local storage data is set through the method userInfo
, and the content is an object {name: 'Tom', age: 20}
. The local storage data is acquired through wx.getStorageSync
the method, and the cached data is output in the console after the acquisition is successful.
It should be noted that the size of the local data storage is limited by the storage capacity of the device. Too much stored data may occupy a large amount of device storage space, causing the device to run slowly or even crash.
The cache and local data storage methods need to be selected according to the actual situation, and factors such as data size and demand can be considered. And clean up unnecessary cache and stored data in time to avoid taking up too much device memory and storage capacity.
Clear local storage:
(1)wx.setStorageSync(); //存储值
(2)wx.removeStorageSync(); // 移除指定的值
(3)wx.getStorageSync(); // 获取值
(4)wx.getStorageInfoSync(); // 获取当前 storage 中所有的 key
(5)wx.clearStorageSync(); // 清除所有的key
clear cache:
(2)wx.removeStorage(); // 移除指定的值
(3)wx.getStorage(); // 获取值
(4)wx.getStorageInfo(); // 获取当前 storage 中所有的 key
(5)wx.clearStorage(); // 清除所有的key