用到的知识
- 列表结构可以通过 v-for 指令结合数据生成
- v-on 结合事件修饰符可以指定某个键,比如 .enter
- 通过 v-model 可以快速的设置和获取表单元素的值
- vue 是一种基于数据的开发方式
关于 data 中使用 return 的问题
因为使用return包裹后数据中变量只在当前组件中生效,不会影响其他组件;而不使用return包裹的数据会在项目的全局可见,会造成变量污染 。
实现效果
代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>记事本</title>
<style>
*{
margin: 0px;
padding: 0px;
box-sizing: border-box;
}
#app {
position: relative;
width: 250px;
height: 500px;
margin: 20px auto;
box-shadow: 10px 10px 20px 10px rgba(0,0,0,0.5);
background-color: #C8A86D;
}
#app h2 {
text-align: center;
line-height: 50px;
}
#app input {
margin-left: 10px;
width: 230px;
height: 30px;
}
#app li {
width: 230px;
height: 40px;
line-height: 40px;
margin: 5px auto 0px;
padding: 5px;
list-style: none;
background-color: #fff;
color: #666;
}
#app li .remove {
width: 30px;
height: 30px;
float: right;
display: none;
text-align: center;
cursor: pointer;
}
#app li:hover .remove{
display: block;
}
#app p {
position: absolute;
left: 10px;
bottom: 10px;
}
#app span {
position: absolute;
right: 10px;
bottom: 10px;
cursor: pointer;
}
</style>
</head>
<body>
<div id="app">
<h2>记事本</h2>
<input type="text" v-model='interText' @keyup.enter='add()' placeholder="请输入文本">
<ul>
<li v-for='(item,index) in list'>
{{index+1}}、{{ item }}
<div class="remove" @click="remove()">
x
</div>
</li>
<p>
{{ listLen }} 项记录
</p>
<span @click="removeall()">
全部清除
</span>
</ul>
</div>
<script src="../vue/vue.min.js"></script>
<script>
let app = new Vue({
el: "#app",
data() {
return {
list:['吃饭饭','睡觉觉','写作业'],
interText:''
}
},
computed: {
listLen: {
get: function() {
return this.list.length
}
}
},
methods: {
add: function() {
this.list.push(this.interText)
this.interText = ''
},
remove: function() {
this.list.splice(this.index,1)
},
removeall: function() {
this.list = []
}
}
})
</script>
</body>
</html>