Vue学习:3.V标签综合3
接上一篇...
V标签综合使用:记事本案例
功能:
在实现列表渲染和删除功能的基础上,增加了数据添加以及数据统计,同时要求底部统计和清空区域在事件数目为0时不显示。
思路:
整体架构分为三部分:头部使用v-model绑定用户输入,并且绑定add方法,通过回车或点击按钮触发数据添加事件;主体部分使用 v-for
渲染数据列表,并在每个列表项内放置一个绑定了 del
方法的“删除”按钮,点击按钮时会触发方法,根据传入的 ID 删除相应数据源中的项目;底部根据数据列表的length显示事件总数,同时设置了“清空”按钮绑定了清空数据数组的方法,此外使用v-show基于数据是否为空决定底部统计区域显示与否。
代码:
html:
<div id="app">
<!-- 头部区域 -->
<header>
<h2>记事本</h2>
<input @keyup.enter="add" v-model="newName" placeholder="请输入任务">
<button @click="add">添加任务</button>
</header>
<!-- 列表区域 -->
<section>
<ul>
<li v-for="(item,index) in list" :key="item.id">
<span>{{ index + 1 }}.</span><label>{{ item.name }}</label>
<Button @click="del(item.id)" style="height: 20px; line-height: 10px;">x</Button>
</li>
</ul>
</section>
<!-- 统计和清空 当任务数为0时,不显示-->
<footer v-show="list.length > 0">
<span>合计:{{ list.length }}</span>
<button @click="del_all">清空任务</button>
</footer>
</div>
js:
<script>
const app = new Vue({
el: '#app',
data: {
newName: '',
list: [
{id: 1, name: '吃喝玩乐'},
{id: 2, name: '打游戏'},
{id: 3, name: '看剧'},
{id: 4, name: '出去玩!'}
]
},
methods: {
del(id){
this.list = this.list.filter(item => item.id != id);
},
add(){
//防止输入为空:为空时提示!
if(this.newName.trim() === ''){
alert('请输入任务!')
return
}
//为保证ID唯一,使用Date()
this.list.unshift({
id: +new Date(),
name: this.newName
}),
//当完成添加后,输入框内清空
this.newName = ''
},
del_all(){
this.list = [];
}
}
})
</script>
css:
(感觉是最难写的部分,当下只追求效果)
<style>
#app{
width: 500px;
text-align: center;
}
header{
background-color: #abc;
}
section{
width: 500px;
background-color: #ffd;
margin-top: -20px;
}
ul{
list-style: none;
text-align: left;
}
li{
height: 50px;
line-height: 50px;
}
footer span{
//“子相父绝”,父元素为整个页面
position: absolute;
left: 10px;
}
footer button{
position: absolute;
left: 350px;
}
</style>
分类:
Vue2
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通