Vue入门:(v-for v-model)

v-for

当需要将一个数组遍历或枚举一个对象循环显示时候,我常用的就是列表渲染指令v-for. 它需要结合着in 或者of来使用。
例如

<li v-for="(item,index) in list" >

这里list是数组名,item为遍历的对象,index对应其下标


v-model

用于在表单类元素上双向绑定数据,例如在输入框上使用时,输入的内容会实时映射到绑定的数据上。

<input type="text" placeholder="请输入任务" v-model="notecontent" />

例如上面html的notecontent和data里的notecontent实现了绑定,同步变换。

var app =new Vue({
    
    
				el:"#app",
				data:{
    
    
					list:[],
					notecontent:"",
					
				}
				})

实例:简单记事本实现

功能

1.通过输入事件回车自动添加显示事件
2.可以动态删除对应事件
3.可以记录当前事件数目
4.可以一次性清空事件

分析

1.通过keyup.enter回车事件将文本框内内容加入list,此时文本框内内容可以通过v-model直接从data内获取
2.要想删除对应事件,可以在v-for中加入index下标,然后index作为点击事件的参数,此时可以通过splice函数删除
3.可以直接用length函数记录事件数
4.直接令list为空即可

代码

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<title>记事本</title>
		<link rel="stylesheet" type="text/css" href="css/notebook.css"/>
	</head>
	
	<style type="text/css">
		body{
     
     
			text-align: center;
		}
		#noteli{
     
     
			list-style-type: none;
		}
		#notediv{
     
     

			height: 25px;
			background-color: #15c1ff;
		}
		#divindex{
     
     
			width: 25px;
			height: 25px;
			float: left;
			color: white;
			background-color: #1070ff;
		}
		#divcontent{
     
     
			float: left;
			color: white;
			margin-left: 15px;
		}
		#divremove{
     
     
			float: right;
		}
 
		#foot{
     
     
			background-color: #1070ff;
			height: 20px;
		}
		#notenum{
     
     
			color: #c2c7c8;
			font-size: 15px;
			float: left;
			
		}
		
		#clear{
     
     
			float: right;
		}
		
	</style>
	<body>
		<h1>记事本</h1>
		<div id="app">
		<input type="text" name="" id="addtext" value="" placeholder="请输入任务" v-model="notecontent" 
		   @keyup.enter="add"/>
          <div id="">
			<ul>
          	    <li v-for="(item,index) in list" id="noteli">
          			<div id="notediv">
          				<div id="divindex">{
   
   { index+1 }}</div>
						<div id="divcontent">  {
   
   { item }}</div>
						<input type="button" name="" id="divremove" value="删除" @click="remove(index)" />
          			</div>
          		</li>
				<div id="foot" v-show="list.length>0">
					<span v-if="list.length>0" id="notenum"><strong id="num">{
   
   {list.length}}</strong>  条记录</span>
					<input type="button" name="" id="clear" value="清空" v-if="list.length>0"  @click="clear"/>
				</div>
		    </ul>
			
          	
          </div>
			
		
		
		</div>
		
		<!-- 对于制作原型或学习,你可以这样使用最新版本: -->
		<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
		<script>
			var app =new Vue({
     
     
				el:"#app",
				data:{
     
     
					list:[],
					notecontent:"",
					
				},
				methods:{
     
     
					add:function(){
     
     
						this.list.push(this.notecontent);
					},
					remove:function(index){
     
     
						this.list.splice(index,1);
					},
					clear:function(){
     
     
						this.list=[];
					}
				}
				
			})
		</script>
		
	</body>
</html>

运行

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_43522998/article/details/109624853