美文网首页
vue双向数据绑定

vue双向数据绑定

作者: 事在人为s | 来源:发表于2018-12-27 21:25 被阅读0次

    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>
    
    

    storage.js

    var storage =  {
    set(key, value) {
        localStorage.setItem(key, JSON.stringify(value)); 
    }, 
    get(key) {
        return JSON.parse(localStorage.getItem(key)); 
    }, 
    remove(key) {
        localStorage.removeItem(key); 
    }
    
    }
    
    export default storage; 
    

    相关文章

      网友评论

          本文标题:vue双向数据绑定

          本文链接:https://www.haomeiwen.com/subject/mladlqtx.html