学习完vue指令 做的一个学生信息录入系统
一.demo实现原理
输入完个人信息后 点击创建用户 数据就会显示在下面的表格中 用到了vue中的数据双向绑定 v-model v-for 还要js正则 数组的unshift splice 等方法 效果如下图

二 完整代码如下 需引入一下vue.js
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script src="vue/vue.js"></script>
<style>
/* 简单写了一下css样式 */
#app{width:600px;margin:50px auto;}
fieldset{border:1px solid orange;width:600px;margin-bottom:30px;}
input{width:200px;height:20px;margin-bottom:20px;}
table{width:600px;border:1px solid orange;}
thead{background-color:orangered;}
</style>
</head>
<body>
<div id="app">
<!-- 第一部分 -->
<fieldset id="">
<legend>学院学生信息录入系统</legend>
<div>
<span>姓名</span>
<!-- v-model是为了实现数据双向绑定 -->
<input type="text" placeholder="请输入姓名" v-model="newuser.name">
</div>
<div>
<span>年龄</span>
<input type="text" placeholder="请输入年龄" v-model="newuser.age">
</div>
<div>
<span>性别</span>
<select name="" id="" style="margin:0px 0px 20px 0px;" v-model="newuser.sex">
<option value ="男">男</option>
<option value ="女">女</option>
</select>
</div>
<div>
<span>手机</span>
<input type="text" placeholder="请输入手机" v-model="newuser.tel">
</div>
<button @click="add()">创建新用户</button>
</fieldset>
<!-- 第二部分 -->
<table>
<thead>
<tr>
<td>姓名</td>
<td>性别</td>
<td>年龄</td>
<td>手机</td>
<td>删除</td>
</tr>
</thead>
<tbody>
<!-- v-for 遍历数组 -->
<tr v-for="(p,index) in user">
<td>{{p.name}}</td>
<td>{{p.sex}}</td>
<td>{{p.age}}</td>
<td>{{p.tel}}</td>
<td><button @click="del(index)">删除</button></td>
</tr>
</tbody>
</table>
</div>
<script type="text/javascript">
new Vue({
el:'#app',
data:{
//自己模拟的一个数据
user:[{name:'张三',sex:'男',age:'20',tel:'1832838'},{name:'李四',sex:'女',age:'22',tel:'15988'}],
//页面上的数据更新在这个对象里面 因为加了v-model
newuser:{name:'',sex:'男',age:'',tel:''}
},
methods:{
add(){
// 这是一些简单的判断
if(this.newuser.name===''){
alert('名字不能为空');
//还原一下newuser对象 以便于下一次输入 以下都是
this.newuser={name:'',sex:'男',age:'',tel:''};
return;
}
if(this.newuser.age<='0'){
alert('年龄要大于0');
this.newuser={name:'',sex:'男',age:'',tel:''};
return;
}
//正则简单验证下 要输入正确的手机号
if(!(/^1(3|4|5|6|7|8|9)\d{9}$/.test(this.newuser.tel))){
alert('请输入正确的手机号');
this.newuser={name:'',sex:'男',age:'',tel:''};
return;
}
// 将newuser放进数组的头部 放进去v-for好遍历出来
this.user.unshift(this.newuser);
//添加完了以后 要还原一下newuser对象 以便于下一次输入
this.newuser={name:'',sex:'男',age:'',tel:''};
},
del(index){
// splice删除点击的那一条数据 index是v-for遍历出来的索引
this.user.splice(index,1);
}
}
})
</script>
</body>
</html>

浙公网安备 33010602011771号