前面用ES6写了一个 todos,这里放一个Vue版本写的,可以通过代码对比,看看Vue和原生js的区别。
点击图片看效果。
核心代码:
const filters = {
all(todos) {
return todos;
},
active(todos) {
return todos.filter(item => !item.completed);
},
completed(todos) {
return todos.filter(item => item.completed);
}
}
const TODO_KEY = 'todo-keys'
const storage = {
get() {
return JSON.parse(localStorage.getItem(TODO_KEY)) || [];
},
set(todos) {
localStorage.setItem(TODO_KEY, JSON.stringify(todos));
}
}
const vm = new Vue({
el: '#app',
data: {
// todos:[
// {id:1, title: '上课', completed: true},
// {id:2, title: '吃饭', completed: false},
// {id:3, title: '睡觉', completed: false},
// {id:4, title: '梦游', completed: false},
// ],
todos: storage.get(),
newTodo: '',
editingTodo: null,
todoBeforeTitle: '',
todoType: 'all'
},
methods: {
pluralize(unit) {
return unit + (this.remaining === 1 ? '' : 's');
},
addTodo(){
const val = this.newTodo.trim();
if(!val) return;
// this.todos.push({id:this.todos.length > 0 ? this.todos[this.todos.length -1].id + 1 : 0 , title: val, completed: false});
this.todos.push({id: Date.now(), title: val, completed: false});
this.newTodo = '';
},
removeTodo(todo) {
const index = this.todos.indexOf(todo);
this.todos.splice(index,1);
},
editTodo(todo) {
this.editingTodo = todo;
this.todoBeforeTitle = todo.title;
},
editDone(todo) {
if(todo !== this.editingTodo) return;
const val = todo.title.trim();
if(!val) {
this.removeTodo(todo);
}else{
todo.title = val;
}
this.editingTodo = null;
this.todoBeforeTitle = '';
},
cancelEdit(todo) {
todo.title = this.todoBeforeTitle;
this.editingTodo = null;
this.todoBeforeTitle = '';
},
removeAllCompleted() {
// this.todos = this.todos.filter(item => !item.completed)
this.todos = filters.active(this.todos);
}
},
computed: {
remaining() {
// return this.todos.filter(item => !item.completed).length;
return filters.active(this.todos).length;
},
allDone:{
get() {
return this.remaining === 0;
},
set(value) {
this.todos.forEach(item => item.completed = value);
}
},
filtersTodo() {
return filters[this.todoType](this.todos);
}
},
directives: {
'todo-focus'(el) {
el.focus();
}
},
watch: {
todos: {
deep: true,
handler: storage.set
}
}
})差不多了,原生js的案例也整理完了,框架的案例就不上了,如果有一天我转行了,可以把所有完整的项目都分享出来,再给自己三个月的时间吧。

发表评论:
◎请发表你卖萌撒娇或一针见血的评论,严禁小广告。