本文實例為大家分享了Vue使用localStorage存儲數據的具體代碼,供大家參考,具體內容如下
通過下面這個案例來了解localStorage的基本使用方法。
輸入評論人、評論內容,點擊發表評論,評論數據將保存到localStorage中,并刷新評論列表。
1.先組織出一個最新評論數據對象
var comment = {id:Date.now(), user:this.user, content:this.content}
2. 把得到的評論對象,保存到localStorage中
1.localStorage只支持存字符串數據,保存先調用JSON.stringify轉為字符串
2.在保存最新的評論數據之前,要先從localStorage獲取到之前的評論數據(string)轉換為一個數組對象,然后把最新的評論,push到這個數組
3.如果獲取到的localStorage中的評論字符串為空,不存在,則可以返回一個'[]'讓JSON.parse去轉換
4.把最新的評論列表數組,再次調用JOSN.stringify轉為數組字符串,然后調用localStorage.setItem()保存
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <link rel="stylesheet" type="text/css" href="../css/bootstrap.css" rel="external nofollow" > </head> <body> <div id='app'> <cmt-box @func="loadComments"></cmt-box> <ul class="list-group"> <li class="list-group-item" v-for="item in list" :key="item.id"> <span class="badge">評論人:{{item.user}}</span> {{item.content}} </li> </ul> </div> <template id="tmp1"> <div> <div class="form-group"> <label>評論人:</label> <input type="text" v-model="user" class="form-control"> </div> <div class="form-group"> <label>評論內容:</label> <textarea class="form-control" v-model="content"></textarea> </div> <div class="form-group"> <input type="button" value="發表評論" class="btn btn-primary" @click="postComment"> </div> </div> </template> </body> <script src="../lib/vue.js"></script> <script> var conmmentBox={ template:'#tmp1', data(){ return{ user:'', content:'' } }, methods:{ postComment(){ //1.評論數據存到哪里去,存放到了localStorage中 //2.先組織出一個最新評論數據對象 //3.想辦法,把第二步得到的評論對象,保持到localStorage中】 // 3.1 localStorage只支持存字符串數據,先調用JSON.stringify // 3.2 在保存最新的評論數據之前,要先從localStorage獲取到之前的評論數據(string)轉換為一個數組對象,然后把最新的評論,push到這個數組 // 3.3 如果獲取到的localStorage中的評論字符串為空,不存在,則可以返回一個'[]'讓JSON.parse去轉換 // 3.4 把最新的評論列表數組,再次調用JOSN.stringify轉為數組字符串,然后調用localStorage.setItem() var comment = {id:Date.now(), user:this.user, content:this.content} //從localStorage中獲取所用的評論 var list = JSON.parse(localStorage.getItem("cmts") || '[]') list.unshift(comment) //重新保存最新的評論數據 localStorage.setItem('cmts',JSON.stringify(list)) this.user = this.content = '' this.$emit('func') } } } var vm = new Vue({ el:'#app', data:{ list:[] }, methods:{ //從本地的localStorage中,加載評論列表 loadComments(){ var list = JSON.parse(localStorage.getItem("cmts") || '[]') this.list = list } }, created(){ this.loadComments() }, components:{ 'cmt-box':conmmentBox } }) </script> </html>
可以打開開發者模式查看localStorage保存的數據
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com