Quasar 提供了 Web 存储 API 的封装器。
¥Quasar provides a wrapper over Web Storage API.
提示
Web Storage API 仅检索字符串。Quasar 使用其原始数据类型检索数据。你告诉它存储一个数字,然后检索它,它仍然是一个数字,而不是像 Web Storage API 那样以字符串形式表示该数字。JSON、正则表达式、日期、布尔值等也相同。
¥Web Storage API only retrieves strings. Quasar retrieves data with its original data type. You tell it to store a Number then to retrieve it and it will still be a Number, not a string representation of the number as with Web Storage API. Same for JSON, Regular Expressions, Dates, Booleans and so on.
关于服务器渲染的说明
在服务器端渲染 (SSR) 版本上运行代码时,此功能无法使用。Web Storage 是一个仅适用于浏览器的 API。但是,你可以在客户端通过 SSR 使用它。
¥When running the code server-side on SSR builds, this feature can’t work. Web Storage is a browser API only. You can however make use of it on the client-side with SSR.
// quasar.config file
return {
framework: {
plugins: [
'LocalStorage',
'SessionStorage'
]
}
}
用法(Usage)
¥Usage
import { LocalStorage, SessionStorage } from 'quasar'
LocalStorage.set(key, value)
let value = LocalStorage.getItem(key)
SessionStorage.set(key, value)
let value = SessionStorage.getItem(key)
import { useQuasar } from 'quasar'
setup () {
const $q = useQuasar()
$q.localStorage.set(key, value)
const value = $q.localStorage.getItem(key)
$q.sessionStorage.set(key, value)
const otherValue = $q.sessionStorage.getItem(key)
}
为了在设置值时确保万无一失,最好还能捕获底层本地/会话存储 Web API 引发的任何潜在错误,例如超出配额时的错误:
¥For a bulletproof approach when setting a value, it’s best to also catch any potential errors raised by the underlying Local/Session Storage Web API, like when exceeding quota:
try {
$q.localStorage.set(key, value)
} catch (e) {
// data wasn't successfully saved due to
// a Web Storage API error
}
提示
要查看方法的详尽列表,请查看 API 部分。
¥For an exhaustive list of methods, please check the API section.
数据类型(Data Types)
¥Data Types
Quasar 存储开箱即用地支持(但不限于)以下数据类型。如果你存储其中一种类型,检索到的数据将具有相同的数据类型。
¥Quasar Storage supports (but not limited to) the following data types out of the box. If you store one of these types, the retrieved data will have the same data type.
日期
¥Dates
正则表达式
¥Regular Expressions
数字
¥Numbers
布尔值
¥Booleans
字符串
¥Strings
普通 JavaScript 对象
¥Plain Javascript Objects
如果你存储任何其他数据类型,返回值将为字符串。
¥If you store any other data type, the returned value will be a String.
因此,你甚至可以存储函数,但请注意,你需要对返回值(该值是函数的字符串表示形式)进行 eval() 操作。
¥So you can even store functions, but be careful that you need to eval() the returned value (which is a String representation of the function).