前端开发笔记[1]-使用浏览器存储数据
摘要
使用vue.js操作cookie,webStoage,indexedDB实现在浏览器存储数据.
平台信息
- macOS
- safari:版本16.6 (18615.3.12.11.2)
- node.js
- "vue": "^2.5.2",
- "vue-router": "^3.0.1"
vue.js简介
[https://cn.vuejs.org/guide/quick-start.html]
[https://cn.vuejs.org/guide/introduction.html#the-progressive-framework]
Vue (发音为 /vjuː/,类似 view) 是一款用于构建用户界面的 JavaScript 框架。它基于标准 HTML、CSS 和 JavaScript 构建,并提供了一套声明式的、组件化的编程模型,帮助你高效地开发用户界面。无论是简单还是复杂的界面,Vue 都可以胜任。
Vue 的两个核心功能:
- 声明式渲染:Vue 基于标准 HTML 拓展了一套模板语法,使得我们可以声明式地描述最终输出的 HTML 和 JavaScript 状态之间的关系。
- 响应性:Vue 会自动跟踪 JavaScript 状态并在其发生变化时响应式地更新 DOM。
webpack简介
[https://www.cnblogs.com/wjw1014/p/15232319.html]
Webpack 是一个前端的静态模块资源打包工具,能让浏览器也支持模块化,他将根据模块的依赖关系进行静态分析,然后将这些模块按照指定的规则生成对应的静态资源。
Webpack是一个现代的JavaScript应用程序的静态模块打包工具(modulebundler).它的主要目标是将应用程序所需的多个模块打包到一个或多个bundle文件中,以便在浏览器中加载
eslint简介
[http://eslint.cn]
ESLint 是一个开源项目,可以帮助你发现并修复 JavaScript 代码中的问题。 不论你的 JavaScript 是在浏览器还是在服务器,是否使用框架,ESLint 都可以帮助你的代码变得更好。
vue+webpack的项目结构
[https://vuex.vuejs.org/guide/structure.html]
- build/
This directory holds the actual configurations for both the development server and the production webpack build. Normally you don't need to touch these files unless you want to customize Webpack loaders, in which case you should probably look at build/webpack.base.conf.js.
- config/index.js
This is the main configuration file that exposes some of the most common configuration options for the build setup. See API Proxying During Development and Integrating with Backend Framework for more details.
- src/
This is where most of your application code will live in. How to structure everything inside this directory is largely up to you; if you are using Vuex, you can consult the recommendations for Vuex applications.
- static/
This directory is an escape hatch for static assets that you do not want to process with Webpack. They will be directly copied into the same directory where webpack-built assets are generated.
See Handling Static Assets for more details.
- test/unit
Contains unit test related files. See Unit Testing for more details.
- test/e2e
Contains e2e test related files. See End-to-end Testing for more details.
- index.html
This is the template index.html for our single page application. During development and builds, Webpack will generate assets, and the URLs for those generated assets will be automatically injected into this template to render the final HTML.
- package.json
The NPM package meta file that contains all the build dependencies and build commands.
浏览器存储
cookie
[https://zhuanlan.zhihu.com/p/468835826]
Cookie 是通过浏览器将服务器返回的数据保存在本地的一小块数据(一般小于4kb)。当浏览器发送请求且浏览器存在 Cookie 时,浏览器会自动在请求头携带上 Cookie 数据。引入 Cookie 的意义是因为 HTTP 的请求是无状态的,如:浏览器发出的请求服务器没办法区分浏览器用户身份以及用户的相关操作状态(可以通过 Cookie 传递这些信息)。最开始 Cookie 被作为唯一的存储手段,但是因为浏览器的每次请求都会携带上 Cookie,会带来额外的开销,而且存储量比较小,所以后来浏览器推出了新的 Api(web stoeage Api和 indexedDb)。
webStorage
[https://www.cnblogs.com/blackbird/archive/2012/06/18/2553718.html]
web storage提供在浏览器端通过key/value的方式存储数据,默认5MB存储空间。包括以下两部分:
- session storage(会话级别的存储,会话结束后失效)
- local storage(持久性存储,用户主动删除或js操作清空)
indexedDB
[https://zhuanlan.zhihu.com/p/343376038]
IndexedDB是一种在浏览器端存储数据的方式。既然称之为DB,是因为它丰富了客户端的查询方式,并且因为是本地存储,可以有效的减少网络对页面数据的影响。
有了IndexedDB,浏览器可以存储更多的数据,从而丰富了浏览器端的应用类型。IndexedDB和传统的关系型数据不同的是,它是一个key-value型的数据库。
实现
#新建项目:
# 全局安装 vue-cli
npm install --global vue-cli
# 创建一个基于 webpack 模板的新项目
vue init webpack learn-sys
#跟随提示一路enter即可
# 安装依赖
cd learn-sys
npm install
项目目录
index.html
./src
├── App.vue
├── assets
│ └── logo.png
├── components
│ ├── HelloWorld.vue
│ ├── cookie.vue
│ ├── indexedDB.vue
│ └── webStorage.vue
├── main.js
└── router
└── index.js
./static
└── mdui
├── css
│ ├── mdui.css
│ ├── mdui.css.map
│ ├── mdui.min.css
│ └── mdui.min.css.map
├── fonts
│ └── roboto
│ ├── LICENSE.txt
│ ├── Roboto-Black.woff
│ ├── Roboto-Black.woff2
│ ├── Roboto-BlackItalic.woff
│ ├── Roboto-BlackItalic.woff2
│ ├── Roboto-Bold.woff
│ ├── Roboto-Bold.woff2
│ ├── Roboto-BoldItalic.woff
│ ├── Roboto-BoldItalic.woff2
│ ├── Roboto-Light.woff
│ ├── Roboto-Light.woff2
│ ├── Roboto-LightItalic.woff
│ ├── Roboto-LightItalic.woff2
│ ├── Roboto-Medium.woff
│ ├── Roboto-Medium.woff2
│ ├── Roboto-MediumItalic.woff
│ ├── Roboto-MediumItalic.woff2
│ ├── Roboto-Regular.woff
│ ├── Roboto-Regular.woff2
│ ├── Roboto-RegularItalic.woff
│ ├── Roboto-RegularItalic.woff2
│ ├── Roboto-Thin.woff
│ ├── Roboto-Thin.woff2
│ ├── Roboto-ThinItalic.woff
│ └── Roboto-ThinItalic.woff2
├── icons
│ └── material-icons
│ ├── LICENSE.txt
│ ├── MaterialIcons-Regular.ijmap
│ ├── MaterialIcons-Regular.woff
│ └── MaterialIcons-Regular.woff2
└── js
├── mdui.esm.js
├── mdui.esm.js.map
├── mdui.js
├── mdui.js.map
├── mdui.min.js
└── mdui.min.js.map
主要代码
src/router/index.js
/* eslint-disable */
import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '@/components/HelloWorld'
//import { getCookie, setCookie } from '@/utils.js'; // 根据你的文件路径进行修改
import cookie from '@/components/cookie'
import localStorage from '@/components/webStorage'
import indexedDB from '@/components/indexedDB'
Vue.use(Router)
const router = new Router({
routes: [
// {
// path: '/',
// name: 'HelloWorld',
// component: HelloWorld
// },
{
path:'/',
name:'indexedDB',
component: indexedDB
},
{
path:'/test_webStorage',
name:'localStorage',
component: localStorage
},
{
path:'/test_cookie',
name:'cookie',
component: cookie
},
],
});
export default router;
src/components/cookie.vue
<script>
/* eslint-disable */
/* 开始自定义函数 */
//获取cookie
export function getCookie(name) {
var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
if (arr = document.cookie.match(reg))
return (arr[2]);
else
return null;
}
//设置cookie,增加到vue实例方便全局调用
export function setCookie(c_name, value, expiredays) {
var exdate = new Date();
exdate.setDate(exdate.getDate() + expiredays);
document.cookie = c_name + "=" + escape(value) + ((expiredays == null) ? "" : ";expires=" + exdate.toGMTString());
}
//删除cookie
export function delCookie(name) {
var exp = new Date();
exp.setTime(exp.getTime() - 1);
var cval = getCookie(name);
if (cval != null)
document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString();
}
export default {
name: 'cookie',
mounted() {
// 设置cookie
setCookie('hello', 'world', 7);
// 获取cookie的值
this.cookieValue = getCookie('hello');
},
data() {
return {
cookieValue: ''
}
}
}
</script>
<template>
<div>
Cookie的值为: {{ cookieValue }}
</div>
</template>
src/components/webStorage.vue
<script>
/* eslint-disable */
export default {
name: 'localStorage',
data() {
return {
storedData: ''
};
},
methods: {
saveData() {
localStorage.setItem('myData', 'hello localStorage');
},
loadData() {
this.storedData = localStorage.getItem('myData');
}
}
};
</script>
<template>
<div>
<button @click="saveData">保存到localStorage</button>
<button @click="loadData">从localStorage加载数据</button>
<br />
<p>webStorage数据:{{ storedData }}</p>
</div>
</template>
src/components/indexedDB.vue
<template>
<div>
<button @click="saveData">保存到IndexedDB</button>
<button @click="loadData">从IndexedDB加载数据</button>
<p>{{ storedData }}</p>
</div>
</template>
<script>
/* eslint-disable */
export default {
name: 'indexedDB',
data() {
return {
storedData: ''
};
},
methods: {
saveData() {
const request = window.indexedDB.open('myDatabase', 1);
request.onerror = (event) => {
console.error('打开数据库失败', event.target.errorCode);
};
request.onsuccess = (event) => {
const db = event.target.result;
const transaction = db.transaction(['myStore'], 'readwrite');
const objectStore = transaction.objectStore('myStore');
const data = { message: 'hello indexedDB' };
const addRequest = objectStore.add(data);
addRequest.onsuccess = () => {
console.log('数据已成功添加到IndexedDB');
};
transaction.oncomplete = () => {
db.close();
};
};
request.onupgradeneeded = (event) => {
const db = event.target.result;
const objectStore = db.createObjectStore('myStore', { keyPath: 'id', autoIncrement: true });
objectStore.createIndex('message', 'message', { unique: false });
};
},
loadData() {
const request = window.indexedDB.open('myDatabase', 1);
request.onerror = (event) => {
console.error('打开数据库失败', event.target.errorCode);
};
request.onsuccess = (event) => {
const db = event.target.result;
const transaction = db.transaction(['myStore'], 'readonly');
const objectStore = transaction.objectStore('myStore');
const getRequest = objectStore.getAll();
getRequest.onsuccess = () => {
if (getRequest.result.length > 0) {
this.storedData = getRequest.result[0].message;
} else {
console.log('IndexedDB中没有数据');
}
};
transaction.oncomplete = () => {
db.close();
};
};
}
}
};
</script>
#运行
npm run dev
#访问:http://localhost:8080/#/
效果
cookie操作 | webStorage操作 | indexedDB操作 |
---|---|---|
![]() |
![]() |
![]() |