vue双向数据绑定
2018-12-27 本文已影响0人
事在人为s
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;