从 jQuery 平滑过渡到 vue (下)- 2
我们继续去年的一个分享,最近开始许多新的分享系列,开拓新的诚然容易而且热情高,我们每人都喜欢尝试新的,这是人性本质,也是人类进步源泉。但是我们需要理智地关心现有的,维护现有的。所以停下来继续维护少量之前的分享。
删除功能
我们需要 vue 端实现这个方法来删除一条 todo 记录
- 我们查看一下在 jquery 中是如何实现删除功能的。
destroy: function (e) { this.todos.splice(this.getIndexFromEl(e.target), 1); this.render(); }
2.而后我们在删除按钮中增加监听 click 的事件 @click=”removeTodo(todo.id)”
<div class="view"> <input class="toggle" v-model="todo.completed" type="checkbox" :checked="todo.completed"> <label>{{ todo.title}}</label> <button class="destroy" @click="removeTodo(todo.id)"></button></div>
我们在 vue 的 method 中相应地实现这个 removeTodo(id) 方法,这里我们用到数组的 filter 方法来过滤掉删除对象。
removeTodo(id){ this.todos= this.todos.filter((todo)=> todo.id != id);},
jv002.JPG
不过当我们再次刷新网页发现,这条记录还在,这是由于我们没有升级 localstorage 中记录。那么我们每一删除都需要调用删除方法吗,这样是不是太麻烦,vue 提供了 watch 让我们可以监控一个对象。
watch: { todos:{ deep:true, handler:'saveTodos' }},
- deep 意思是深层复制
- handler 使我们句柄
而后我们就写我们的句柄 saveTodos 我们调用一下 store 方法。
saveTodos(){ this.store('todos-jquery',this.todos)},
挑选功能
接下来就做我们的转移挑选功能,先看一下 jquery 中是如何实现挑选的
getActiveTodos: function () { return this.todos.filter(function (todo) { return !todo.completed; }); }, getCompletedTodos: function () { return this.todos.filter(function (todo) { return todo.completed; }); }, getFilteredTodos: function () { if (this.filter === 'active') { return this.getActiveTodos(); } if (this.filter === 'completed') { return this.getCompletedTodos(); } return this.todos; },
- 首先我们将这些方法复制到 computed 中去
- 我们修改少量这方法名称,去掉前面的 get。
computed: { activeTodos() { return this.todos.filter(function (todo) { return !todo.completed; }); }, completedTodos() { return this.todos.filter(function (todo) { return todo.completed; }); }, filteredTodos() { if (this.filter === 'active') { return this.activeTodos(); } if (this.filter === 'completed') { return this.completedTodos(); } return this.todos; } },
说明
1. 本站所有资源来源于用户上传和网络,如有侵权请邮件联系站长!
2. 分享目的仅供大家学习和交流,您必须在下载后24小时内删除!
3. 不得使用于非法商业用途,不得违反国家法律。否则后果自负!
4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解!
5. 如有链接无法下载、失效或广告,请联系管理员处理!
6. 本站资源售价只是摆设,本站源码仅提供给会员学习使用!
7. 如遇到加密压缩包,请使用360解压,如遇到无法解压的请联系管理员
开心源码网 » 从 jQuery 平滑过渡到 vue (下)- 2
1. 本站所有资源来源于用户上传和网络,如有侵权请邮件联系站长!
2. 分享目的仅供大家学习和交流,您必须在下载后24小时内删除!
3. 不得使用于非法商业用途,不得违反国家法律。否则后果自负!
4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解!
5. 如有链接无法下载、失效或广告,请联系管理员处理!
6. 本站资源售价只是摆设,本站源码仅提供给会员学习使用!
7. 如遇到加密压缩包,请使用360解压,如遇到无法解压的请联系管理员
开心源码网 » 从 jQuery 平滑过渡到 vue (下)- 2