14-7-4
將 localStorage 做成 plugin
- localStorage的用法:
- https://developer.mozilla.org/zh-TW/docs/Web/API/Window/localStorage
- https://medium.com/%E9%BA%A5%E5%85%8B%E7%9A%84%E5%8D%8A%E8%B7%AF%E5%87%BA%E5%AE%B6%E7%AD%86%E8%A8%98/javascript-localstorage-%E7%9A%84%E4%BD%BF%E7%94%A8-e0da6f402453
- 建立plugin/localStorage.js
export default ({ app }, inject) => {
inject("localStorage", {
set(key = "", val = {}) {
localStorage.setItem(key, JSON.stringify(val));
},
get(key = "") {
const obj = JSON.parse(localStorage.getItem(key));
// 避免傳回 null
if (!obj) {
return {};
}
return obj;
},
remove(key = "") {
localStorage.removeItem(key);
},
removeAll() {
localStorage.clear();
}
});
};
- 加入nuxt.config.js設定
plugins: [
"~/plugins/hello.js",
"~/plugins/axios.js",
"~/plugins/notification.js",
"~/plugins/localStorage.js"
],
- 如此,便可方便的localStorage使用
mounted() {
this.$hello("我在前端被mounted了");
this.$localStorage.set("userData", { name: "tad", age: 48 });
console.log('userData', this.$localStorage.get("userData"));
},