json.parse 和json.stringify 这个api特别好用,接下来用一个存储本地数据的实例来说明下用法:
该实例主要完整一个输入,然后显示,刷新也不会消失的效果,
js中的json.parse 和json.stringify 的使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 | <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <script src="vue2.5.16.js"></script> </head> <body> <div id="app"> <input type="" v-model="message"> <input type="submit" value="提交" @click="add"> <ul> <li v-for="item in data">{{item.text}}</li> </ul> </div> </body> </html> <script> new Vue({ el:"#app", data:{ message:'', data:[] }, created(){ //生命周期钩子函数,开局就触发,保证数据读取显示 this.load() }, methods:{ add(){ var json = { text:this.message }; this.data.push(json) console.log(this.data); localStorage.setItem('data',JSON.stringify(this.data)); }, load(){ console.log(); this.data=JSON.parse(localStorage.getItem('data')); } } }) //JSON.parse 读取 //JSON.stringify 写入 //使用JSON.parse转换为json格式,否则就是字符串 </script> |
1 | 需要注意: |
JSON.parse 一般用作读取
JSON.stringify 一般用于转换格式后存入localStoragez中 json直接存入是一个对象, 解析不了
参考资料:
https://blog.csdn.net/pika_lzy/article/details/79212476
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
7