一个可以综合练习vue指令的小案例。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
*{
margin: 0;
padding: 0;
box-sizing: border-box;
}
body{
background-color: #eee;
}
#app{
margin: 100px auto;
width: 440px;
min-height: 320px;
}
h1{
color: #2980b9;
margin-bottom: 15px;
text-align: center;
}
.box{
padding: 12px;
box-shadow: 8px 8px 4px rgba(0, 0, 0, 0.35);
background-color: #fff;
display: flex;
flex-direction: column;
}
.input{
width: 100%;
height: 42px;
border: 3px solid #34495e;
display: flex;
align-items: center;
}
.input input {
border: none;
height: 100%;
padding-left: 8px;
flex-grow: 1;
}
.input button {
border: none;
width: 72px;
height: 100%;
background-color: #3498db;
cursor: pointer;
}
.content {
line-height: 52px;
}
.content p{
height: 52px;
border-bottom: 3px solid #eee;
display: flex;
justify-content: space-between;
}
.content p span{
display: inline-block;
cursor: pointer;
}
.footer{
margin-top: 12px;
display: flex;
justify-content: space-between;
}
.footer span:last-child{
cursor: pointer;
}
</style>
</head>
<body>
<div id="app">
<h1>记事本</h1>
<div class="box">
<div class="input">
<input v-model="content" type="text">
<button @click="add()">添加任务</button>
</div>
<div class="content">
<p v-for="item in list" :key="item.id">
{{item.id}}、{{item.content}}
<span @click="sub(item.id)">x</span>
</p>
</div>
<div class="footer">
<span>合计:{{total === 0 ? '':total}}</span>
<span @click="all()">清空任务</span>
</div>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
<script>
const app = new Vue({
data() {
return {
list:[
],
total:0,
content:''
}
},
methods: {
add(){
if(this.content.trim() === '') return
this.total = this.list.length + 1
this.list.push({id:this.total,content:this.content})
this.content = ''
},
sub(id){
this.list = this.list.filter(item => item.id !== id)
this.total = this.list.length
},
all(){
this.list = []
this.total = this.list.length
}
},
}).$mount('#app')
</script>
</body>
</html>