Vue 中如何用localStorage来存储

在写个list的小demo时,经常会遇到下面这个问题

113059_tNxz_2261111.png

当刷新后,下面的list就都不见了。因此可以用localStorage。localStorage就是用来本地存储数据的。先看下完整的代码:

vue文件:

<template>
  <div id="app">
    <h2 v-text="title"></h2>
    <input type="text" v-model="newItem" v-on:keyup.enter="addNew"/>
    <ul>
      <li v-for="item in items" v-on:click="toggleFinish(item)" v-bind:class="{finished:item.isFinished}">{{item.label}}</li>
    </ul>
  </div>
</template>

<script>
import Store from './store.js'
console.log(Store)
export default {
  data:function(){
    return{
      items:Store.fetch(),
      title:"to do a list",
      newItem:''

    }
  },
  watch:{
    items:{
      handler:function(items){
        Store.save(items)
      },
      deep:true//深复制
    }
  },
  methods:{
    toggleFinish:function(item){
      item.isFinished=!item.isFinished
    },
    addNew:function(){
      this.items.push({
        label:this.newItem,
        isFinished:false
      })
      this.newItem=''
    }
  }
}
</script>

<style>
#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
.finished{
  text-decoration:underline;
}
</style>

store.js文件

const STORAGE_KEY='todos-vuejs'
export default{
    fetch(){
        return JSON.parse(window.localStorage.getItem(STORAGE_KEY)||'[]')
    },
    save(items){
        window.localStorage.setItem(STORAGE_KEY,JSON.stringify(items))
    }
}

结果:

113453_lbMk_2261111.png

具体关键点如下:

1、通常新输入的数据要先保存在本地,然后刷新时,要从本地读取新数据,所以store.js文件中一个fecth读取数据函数,一个save保存数据函数。

2、store.js写好后,要引入该js文件

113647_AFpy_2261111.png

3、用watch来监听输入数据的变化,有变化时就调用save函数保存变化

113724_vtBf_2261111.png

其中deep:true是深复制,就是不仅是数据,连其状态什么的都一块复制了,如例子中的isFinished就复制了

113843_4vsI_2261111.png

4、到这里只是保存了新添加的数据在本地,但是还需要读取出来

113959_zzWu_2261111.png

调用fetch函数就可以吧新数据读取出来。

转载于:https://my.oschina.net/zhangxuman/blog/1522732

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值