刚学vue.js不久,做个小玩具练练手。
代码不是很多,方便起见,使用的框架文件全部在线引入。
心得记录
页面元素组成,一个大容器div包裹,其中:
一个div做头部。包含一个超链接,指向下面的折叠div。
一个div折叠显示,包含输入框。v-model双向绑定输入框的值与data中的input。v-on绑定keydown事件,加了修饰符enter,回车键按下时执行定义在Vue实例中methods下的createTip函数。new Date()获取当前系统时间。创建一条便签,push()加至末尾。创建结束后清除input的值。
一个ul放便签内容。v-show控制提示项的显示与隐藏。v–for渲染数据(li使用template标签包裹),使用了下标模式。v-bind绑定title属性,鼠标放在该项内容上时显示该条便签的创建时间。每项附带一个删除图标(原本的超链接功能通过href=”javascript:;“取消),直接使用css :hover伪类样式控制显隐,v-on绑定click事件,执行deleteTip函数,此函数使用每项的下标做参数。函数内调用splice(index,num)函数删除对应下标元素。
最后一个div做底部。总条数由Vue计算属性得出。以及最后的超链接执行清空操作。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>便签</title>
<link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/4.3.1/css/bootstrap.min.css">
<script src="https://cdn.staticfile.org/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdn.staticfile.org/popper.js/1.15.0/umd/popper.min.js"></script>
<script src="https://cdn.staticfile.org/twitter-bootstrap/4.3.1/js/bootstrap.min.js"></script>
<style>
ul,li{
list-style: none;
}
a,a:hover{
text-decoration: none;
}
.bg-paper{
background:rgb(255, 255, 249);
}
.note{
width:500px;
margin: 30px auto;
}
.list-group li> a{
visibility: hidden;
}
.list-group li:hover > a{
visibility: visible;
}
</style>
</head>
<body>
<script src="https://cdn.staticfile.org/vue/2.2.2/vue.min.js"></script>
<div class="container" id="note">
<div class="note card bg-paper shadow-sm">
<div class="card-header d-flex justify-content-between">
<span class="h5">便签</span>
<a class="text-secondary" type="button" data-toggle="collapse" href="#newTip">添加</a>
</div>
<div class="collapsing" id="newTip">
<input type="text" class="form-control text-center border-0 rounded-0"
placeholder="Enter键创建" v-model="input" @keydown.enter="createTip">
</div>
<ul class="list-group list-group-flush">
<li class="list-group-item" v-show="tips.length==0">无</li>
<template v-for="(tip,i) in tips">
<li class="list-group-item list-group-item-action d-flex justify-content-between">
<div class="badge badge-dark p-2">{{i+1}}</div>
<div class="flex-fill px-2" :title="tip.date">{{tip.content}}</div>
<a href="javascript:;" class="text-danger" @click="deleteTip(i)">×</a>
</li>
</template>
</ul>
<div class="card-footer d-flex justify-content-between">
<span class="h6 text-muted">共{{totalNum}}条</span>
<span><a href="javascript:;" class="text-secondary" @click="clearTip">清空</a></span>
</div>
</div>
</div>
<script>
var v = new Vue({
el:"#note",
data:{
tips:[],
input:"",
},
computed:{
totalNum(){//总条数
return this.tips.length;
}
},
methods:{
createTip(){//新便签 内容+时间
if(this.input==""){
return;
}
var date = new Date();
this.tips.push({"content":this.input,"date":date});
this.input="";
},
deleteTip(i){//删除指定下标的便签
this.tips.splice(i,1);
},
clearTip(){
this.tips=[];
}
}
})
</script>
</body>
</html>
效果如下
无内容时:
添加便签后: