v-for、v-model、v-show、v-on小黄记事本案例
-
响应式数组方法:
-
push()添加
-
pop()删除数组最后一个元素
-
shift()删除数组的第一个元素
-
unshift()在数组最前面添加元素
-
splice()的作用:删除元素,插入元素,替换元素。
- 删除元素:第二个参数传入要删的几个元素(如果没有将删除后面所有元素)。
- 替换元素:第二个参数,表示我们要替换几个元素,后面的用于替换前面的元素。
- 插入元素:第二个参数,传入数据,并且后面要插入的元素。
-
sort()排序
-
reverse()反转
-
小黄记事本功能: 新增 删除 统计 清空 隐藏
-
新增:
- 生成列表结构(v-for 数组)
- 获取用户输入(v-model双向数据绑定)
- 回车,新增数据(v-on .enter添加数据)
-
删除:
- 点击删除指定内容(v-on splice 索引) 传参
-
统计:
- doIt.length 清空: this.doIt=[];
-
隐藏:
- 没有数据,隐藏元素(v-show --> v-show=“doIt.length!=0”)
-
css样式:
*{ margin:0; padding: 0; list-style: none; } #todoapp{ width: 600px; height: 600px; margin: 50px auto; background-color: pink; } .header{ text-align: center; } .header h1{ color: red; font-size: 40px; font-weight: 100; line-height: 100px; } .header input::-webkit-input-placeholder{ color: rgb(180, 178, 178); font-size: 16px; } .new-todo{ padding-left: 10px; width: 390px; height: 50px; outline:none; border: 2px solid rgb(233, 228, 229); } .main{ width: 100%; } .main ul li{ width: 390px; height: 45px; padding-left: 10px; line-height: 45px; margin:0 auto; font-size: 18px; color: rgb(138, 136, 136); border-left:2px solid rgb(233, 228, 229) ; border-right:2px solid rgb(233, 228, 229) ; border-bottom:2px solid rgb(233, 228, 229) ; position: relative; } .footer{ width: 390px; height: 45px; padding-left: 10px; line-height: 45px; margin:0 auto; border-left:2px solid rgb(233, 228, 229) ; border-right:2px solid rgb(233, 228, 229) ; border-bottom:2px solid rgb(233, 228, 229) ; position: relative; color: rgb(138, 136, 136); } button{ width: 30px; height: 45px; border:none; outline:none; background-color: transparent; position: absolute; right: 10px; color: rgb(180, 178, 178); }
<body> <!-- 2.html结构 --> <!-- 主体区域 --> <section id="todoapp"> <!-- 输入框 --> <header class="header"> <h1>小黄记事本</h1> <input autofocus="autofocus" autocomplete="off" v-model="message" @keyup.enter="add" placeholder="请输入任务" class="new-todo"> </header> <!-- 列表区域 --> <section class="main"> <ul> <!-- <li>1. 写代码</li> --> <li v-for="(it,index) in doIt"> {{index+1}}--->{{it.name}} <button class="destroy" @click="remove(index)">删除</button> </li> </ul> </section> <!-- 统计和清空 --> <footer class="footer" v-show="doIt.length!=0"> <span>{{doIt.length}}项目</span> <button @click="clearAll">清空</button> </footer> </section> <!-- 1.开发环境版message本,包含了有帮助的命令行警告 --> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <!-- 3.创建Vue实例 --> <script> var app = new Vue({ el:"#todoapp", data:{ message:"", doIt:[ {name:"写代码"} ], }, methods:{ add:function(){ this.doIt.push({name:this.message}); }, remove:function(index){ // 删除 this.doIt.splice(index,1);//索引删除index,删除个数1 }, clearAll:function(){ // 清空数组 this.doIt=[]; } } }) </script> </body>