标签:button session 数组 name 持久化存储 data 留言板 head inter
js 的 Array 操作
- 尾增:arr.push(ele)
- 首增:arr.unshift(ele)
- 尾删:arr.pop()
- 首删:arr.shift()
- 增删改插:arr.splice(begin_index, count, args)
前台数据库
存
持久化存储,永久保存
localStorage.name = "kai";
localStorage["name"] = ‘kai‘;
持久化存储,生命周期同所属标签(页面),页面关闭,重新打开就会丢失
sessionStorage.name = "kai";
取
var a = localStorage.key console.log(a)
var b = localStorage[‘key‘] console.log(b)
console.log(localStorage.name);
console.log(sessionStorage.name);清空所有
localStorage.clear();
sessionStorage.clear();清空一对
localStorage.removeltem("a")
短板:只能存储字符串,所有对象和数组需要转换为json类型字符串,再进行存储
let a = [1, 2, 3];
localStorage.arr = JSON.stringify(a);
let b = JSON.parse(localStorage.arr);
console.log(b);
案例
留言板
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script> <link href="https://cdn.bootcss.com/twitter-bootstrap/3.4.1/css/bootstrap.min.css" rel="stylesheet"> <script src="https://cdn.bootcss.com/twitter-bootstrap/3.4.1/js/bootstrap.min.js"></script> <style> li:hover { color: red; cursor: pointer; } </style> </head> <body> <div id="app"> <form> <input type="text" v-model="info"> <button type="button" @click="sendInfo">留言</button> </form> <ul> <li v-for="(info, index) in info_arr" @click="deleteInfo(index)">{{info}}</li> </ul> </div> </body> <script src="js/vue.js"></script> <script> new Vue({ el: '#app', data: { info: '', // 三目运算符: 条件 ? 结果1 : 结果2 info_arr: localStorage.info_arr ? JSON.parse(localStorage.info_arr) : [], }, methods: { sendInfo () { // 完成留言:将 info 添加到 info_arr // 增 push unshift | 删 pop shift if (this.info){ // 留言 this.info_arr.push(this.info); // 清空输入框 this.info = ''; // 前台数据持久化(缓存) localStorage.info_arr = JSON.stringify(this.info_arr) } }, deleteInfo (index) { // 删 this.info_arr.splice(index, 1); // 同步给数据库 localStorage.info_arr = JSON.stringify(this.info_arr); } } }) </script> </html>
splice
总结:
Array操作 arr.push(ele) arr.unshift(ele) arr.pop() arr.shift() arr.splice(begin_index, count, args)
前台数据库 localStorage | sessionStorage 1 操作就类似于obj,直接 .key 语法访问 value 2 localStorage永久存储 3 sessionStorage生命周期同所属页面标签
标签:button session 数组 name 持久化存储 data 留言板 head inter
原文地址:https://www.cnblogs.com/kai-/p/12305909.html