上一篇:Vue的指令
https://blog.csdn.net/m0_67930426/article/details/134599378?spm=1001.2014.3001.5501
本篇所需指令: v- for v-model v-on v-show
目录
删除功能
添加功能
统计功能
清空功能
v-show
删除功能
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id="app">
<header>
<h1>记事本</h1>
<input placeholder="请输入任务" />
<button class="add">添加任务</button>
</header>
<section class="main">
<div class="main">
<ul class="do-list">
<li class="todo" v-for="(item,index) in list" :key="item.id">
<div class="view">
<span class="index">{{index+1}}.</span><label>{{item.text}}</label>
<button @click="del(item.id)" class="destroy" >x</button>
</div>
</li>
</ul>
</div>
</section>
<footer class="footer">
<span class="count">合计:<strong>2</strong></span>
<button class="clear" >清空任务</button>
</footer>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue@2.7.14/dist/vue.js"></script>
<script>
var app=new Vue({
el:'#app',
data:{
list:[
{id:1,text:'记得带语文书'},
{id:2,text:'记得带数学书'},
]
},
methods:{
del(id){
this.list=this.list.filter(item=> item.id!==id)
}
}
});
</script>
</body>
</html>
添加功能
add(){
if(this.thing.trim()===''){
alert('请输入任务名称')
return
}
this.list.unshift({
id:"",
text: this.thing,
})
}
这里主要使用了v-model指令,通过v-model指令绑定输入框,获取表单元素的内容
unshift() 方法可向数组的开头添加一个或更多元素,并返回新的长度。
统计功能
核心是计算数组的长度
清空功能
原理: 点击清空按钮,将原数组变为空数组
v-show
当点击清空按钮的时候,将底部隐藏
all-functions
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <div id="app"> <header> <h1>记事本</h1> <input v-model="thing" placeholder="请输入任务" /> <button @click="add()">添加任务</button> </header> <section class="main"> <div class="main"> <ul class="do-list"> <li class="todo" v-for="(item,index) in list" :key="item.id"> <div class="view"> <span class="index">{{index+1}}.</span><label>{{item.text}}</label> <button @click="del(item.id)" class="destroy" >x</button> </div> </li> </ul> </div> </section> <footer class="footer" v-show="list.length>0"> <span class="count">合计:<strong>{{list.length}}</strong></span> <button @click="clear()" >清空任务</button> </footer> </div> <script src="https://cdn.jsdelivr.net/npm/vue@2.7.14/dist/vue.js"></script> <script> var app=new Vue({ el:'#app', data:{ thing:'', list:[ {id:1,text:'记得带语文书'}, {id:2,text:'记得带数学书'}, ] }, methods:{ del(id){ this.list=this.list.filter(item=> item.id!==id) }, add(){ if(this.thing.trim()===''){ alert('请输入任务名称') return } this.list.unshift({ id:"", text: this.thing, }) }, clear(){ this.list=[] } } }); </script> </body> </html>