vue双向数据绑定

僤鯓⒐⒋嵵緔 提交于 2020-02-13 02:22:05

App.vue

 

<template>
  <div id="app">
    <input type="text" v-model="todo" v-on:keydown="keydown($event)">
    <button v-on:click="add">新增</button>
    <br>
    <h2>未完成</h2>
    <ul>
      <li v-for="(item,key) in list" v-if="!item.check">
        <input type="checkbox" v-model="item.check" v-on:change="saveList()">
        {{item}} --------
        <button v-on:click="remove(key)">删除</button>
      </li>
    </ul>
    <br>
    <h2>已完成</h2>
    <ul>
      <li v-for="(item,key) in list" v-if="item.check">
        <input type="checkbox" v-model="item.check" v-on:change="saveList()">
        <input type="checkbox">
        {{item}} --------
        <button v-on:click="remove(key)">删除</button>
      </li>
    </ul>
  </div>
</template>

<script>
import storage from "./model/storage.js";

export default {
  name: "app",
  data() {
    return {
      todo: "",
      list: []
    };
  },
  methods: {
    add() {
      this.list.push({
        text: this.todo,
        check: false
      });
      this.todo = "";
      storage.set("list", this.list);
      //localStorage.setItem("list", JSON.stringify(this.list));
    },
    remove(key) {
      this.list.splice(key, 1);
      storage.set("list", this.list);
      //localStorage.setItem("list", JSON.stringify(this.list));
    },
    keydown(e) {
      if (e.keyCode == 13) {
        this.list.push({
          text: this.todo,
          check: false
        });
        this.todo = "";
        storage.set("list", this.list);
        //localStorage.setItem("list", JSON.stringify(this.list));
      }
    },
    saveList() {
      storage.set("list", this.list);
    }
  },
  mounted() {
    //var list = JSON.parse(localStorage.getItem("list"));
    var list = storage.get("list");
    if (list) {
      this.list = list;
    }
  }
};
</script>

 

 

 1 var storage =  {
 2 set(key, value) {
 3     localStorage.setItem(key, JSON.stringify(value)); 
 4 }, 
 5 get(key) {
 6     return JSON.parse(localStorage.getItem(key)); 
 7 }, 
 8 remove(key) {
 9     localStorage.removeItem(key); 
10 }
11 
12 }
13 
14 export default storage; 
storage.js

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!