vue学习三,localStorage存储todolist(慕课网学习笔记)

1.LocalStorage 是HTML5 本地存储

2.store.js

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

3.App.vue中引入store.js

import Store from './store'; 

4.添加数组更改的监听事件,存入LocalStorage

watch:{
     //监听数组更改
     items:{
        handler:function(items){
             Store.save(items);//存储window.localStorage
        },
        deep:true //深层更改
     }
  }

5.页面初始化的值从LocalStorage中取出

items: Store.fetch()

6.完整代码

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

<script>
import Store from './store'; //调用store.js方法
export default {
  data () {
    return {
       title: 'this is a todo list',
       items: Store.fetch(), //存储记事的数组,从window.localStorage里取出存储的数据
       newItem:'' //绑定input输入的值
    }
  },
  methods:{
     //点击记事完成的事件,isFinished取反,添加下划线
     toggleFinish:function(item){
        item.isFinished=!item.isFinished;
     },
     //新建记事
     addNew:function(){
        this.items.push({
           label:this.newItem,
           isFinished:false
        });
        this.newItem="";//清空重置,双向绑定
     }
  },
  watch:{
     //监听数组更改
     items:{
        handler:function(items){
             Store.save(items);//存储window.localStorage
        },
        deep:true //深层更改
     }
  }
}
</script>

<style>
.finished{text-decoration:underline;}
</style>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值