有时候,我们对数据的控制达不到要求,例如使用本地存储的时候,只存储了标题,但是勾选之后状态应该更新,但是刷新之后状态并没有被保存,这个时候我们就要用到深度的数据监控
watch的使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| watch: {
//监控数据不严格,达不到要求
/*list(){
store.save('aaa',this.list);
}*/
//深度监控 可以监控到细微的变化
/* */
list: {
handler() {
store.save('aaa', this.list);
},
deep: true
}
} |
详细源码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
| <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Document</title>
<style type="text/css">
.value {
width: 500px;
height: 50px;
}
span {
display: inline-block;
width: 300px;
height: 50px;
border: 1px solid black;
line-height: 50px;
text-align: center;
}
.rad {
width: 50px;
height: 50px;
}
.color {
color: #ccc;
background: #f1f1f1;
font-weight: 700;
font-size: 20px;
}
</style>
</head>
<script src="https://cdn.bootcss.com/vue/2.5.17-beta.0/vue.min.js"></script>
<body>
<div id="app">
<h2>添加任务</h2>
<input type="text" name="" class="value" @keyup.13="add" v-model="val">
<div>
<span v-show="list.length">{{list.length}}个任务未完成</span>
<span v-show="!list.length">没有任务</span>
<span>所有任务</span>
<span>未完成的任务</span>
<span>完成的任务</span>
<ul>
<li v-for="item,index in list">
<input type="checkbox" name="" v-model="item.isCheckbox">
<i :class="{color:item.isCheckbox}">{{item.title}}</i>
<span @click="del(index)">删除</span>
</li>
</ul>
</div>
</div>
</body>
</html>
<script type="text/javascript">
//封装localStorage中的数据
var store = {
save(key, value) {
localStorage.setItem(key, JSON.stringify(value));
},
fetch(key) {
return JSON.parse(localStorage.getItem(key)) || [];
}
}
var list = store.fetch("aaa");
console.log(list);
new Vue({
el: "#app",
data: {
list: list,
val: ""
},
methods: {
add(ev) {
console.log(ev);
if (ev.keyCode === 13) {
this.list.push({
title: this.val
})
};
this.val = '';
},
del(index) {
console.log(index);
this.list.splice(index, 1)
}
},
watch: {
//监控数据不严格,达不到要求
/*list(){
store.save('aaa',this.list);
}*/
//深度监控 可以监控到细微的变化
/* */
list: {
handler() {
store.save('aaa', this.list);
},
deep: true
}
}
})
</script> |
「梦想一旦被付诸行动,就会变得神圣,如果觉得我的文章对您有用,请帮助本站成长」
共 0 条评论关于"Watch深度监控数据"
最新评论