官网
安装依赖的css,js
$npm install
<script src="js/vue.js">script>
在app.js中,实例化Vue,然后定义初始化数据
{ //为了形成块级作用域()()
let vm = new Vue({
el: '#app',
data: {
datas: [
{id: 121,title: 'html5',isCompleted: false},
{id: 122,title: 'css3',isCompleted: false},
{id: 123,title: 'js6',isCompleted: false},
]
}
})
如果当前的isCompleted是true,就是显示选中状态
<li :class="{completed: isCom}" v-for="(item,index) in datas">
<div class="view">
<input class="toggle" type="checkbox">
<label>{{ item.title }}label>
<button class="destroy">button>
div>
<input class="edit" value="Create a TodoMVC template">
li>
<input class="new-todo" placeholder="What needs to be done?" v-model="val">
val: '', //显式声明 输入框数据
<input class="new-todo" placeholder="What needs to be done?" @keyup.enter="addItem" v-model="val">
methods: {
addItem(){
if(this.val){ //val存在或者非空的时候才会去添加
this.datas.push({
//console.log(new Date().getTime());
id: new Date().getTime(), //为了保持id的唯一
title: this.val,
isCompleted: false,
});
this.val = ''; //填完数据以后清空输入框的内容
}
}
}
通过一个方法来计算数组数据的长度
methods: {
addItem(){
if(this.val){ //val存在或者非空的时候才会去添加
this.datas.push({
//console.log(new Date().getTime());
id: new Date().getTime(), //为了保持id的唯一
title: this.val,
isCompleted: false,
});
this.val = ''; //填完数据以后清空输入框的内容
}
},
clearCompleted(){
let arr = [];
//遍历datas,如果当前选项是未选中,就把它留下
this.datas.forEach(function(elem){
if(!elem.isCompleted){
arr.push(elem);
}
},this)
this.datas = arr;
}
}
首先绑定计算属性
<span class="todo-count"><strong>{{ legTotal }}strong> item leftspan>
通过v-show来控制显示隐藏
<button class="clear-completed" v-show="isShowClear">Clear completedbutton>
//在计算属性中
compluted: {
isShowClear(){
for(let i=0;i<this.datas.length;i++){
if(this.datas[i].isCompleted){
return true
}
}
return false
}
}
绑定点击事件
<button class="clear-completed" v-show="isShowClear" @click="clearCompleted">Clear completedbutton>
在方法中写这个点击事件
clearCompleted(){
let arr = [];
//遍历datas,如果当前选项是未选中,就把它留下
this.datas.forEach(function(elem){
if(!elem.isCompleted){
arr.push(elem);
}
},this)
this.datas = arr;
},
添加点击事件
<button class="destroy" @click="removeCurrent(index)">button>
removeCurrent(index){
this.datas.splice(index,1);
}
点击全选如果是true,让数据全部变成非选中状态;
<input id="toggle-all" class="toggle-all" type="checkbox" @click="checkedAll">
//在方法中
checkedAll(){
if(this.isCheckedAll){ //全部选中
this.datas.forEach(elem=>{
elem.isCompleted = false;
})
}else{
this.datas.forEach(elem=>{
elem.isCompleted = true;
})
}
this.isCheckedAll = !this.isCheckedAll;
}
大家可以练习练习。
本文源自:https://www.cnblogs.com/guanqiweb/p/9825286.html
作者原文:https://guanqi.xyz/note/todocmvc-practice-vue-version/