具体如图所示:
HTML的格式:
<template>
<div>
<form>
<p style="font-size: 20px">信息调查</p>
<p>
姓名:<input
type="text"
placeholder="请输入姓名"
v-model="newPerson.name"
/>
</p>
<p>年龄:<input type="text" value="0" v-model="newPerson.age" /></p>
<p>
性别:<select v-model="newPerson.sex">
<option>男</option>
<option>女</option>
</select>
</p>
<button type="button" @click="chuang">创建新用户</button>
<span style="font-size: 12px; color: red">{{ tishi }}</span>
</form>
<table>
<tr id="tr1" style="background-color: deepskyblue">
<th>姓名</th>
<th>性别</th>
<th>年龄</th>
<th>操作</th>
</tr>
<tr v-for="(item, index) in people" :key="index">
<td>
<span v-show="!item.edit">{{ item.name }}</span>
<input type="text" v-model="item.name" v-show="item.edit" />
</td>
<td>
<span v-show="!item.edit">{{ item.sex }}</span>
<input type="text" v-model="item.sex" v-show="item.edit" />
</td>
<td>
<span v-show="!item.edit">{{ item.age }}</span>
<input type="text" v-model="item.age" v-show="item.edit" />
</td>
<td>
<button @click="shanchu(index)">删除</button>
<button @click="fn(item)">{{ item.bianji }}</button>
</td>
</tr>
</table>
</div>
</template>
VUE的格式:
<script>
export default {
data() {
return {
tishi: "",
newPerson: {
name: "",
sex: "男",
age: "",
edit: false,
bianji: "编辑",
},
people: [
{
name: "张三",
sex: "男",
age: "25",
edit: false,
bianji: "编辑",
},
],
};
},
methods: {
chuang: function () {
if (this.newPerson.name == "") {
this.tishi = "用户名不能为空!";
return;
}
if (this.newPerson.age == "" || isNaN(this.newPerson.age)) {
this.tishi = "用户年龄不能为空!且必须是数字";
return;
}
//console.log(this);
this.people.splice(this.newPerson.length,0,this.newPerson);
this.newPerson = { name: "", age: "", sex: "男", bianji: "编辑" };
this.tishi = "";
},
shanchu: function (index) {
this.people.splice(index, 1);
},
fn(item) {
item.edit = !item.edit;
if (item.bianji == "编辑") item.bianji = "确定";
else if (item.bianji == "确定") item.bianji = "编辑";
if (item.name == "") {
alert("姓名不能为空");
item.edit = true;
item.bianji = "确定";
return;
}
if (item.age == "" || isNaN(item.age)) {
alert("年龄不能为空且必须是数字");
item.edit = true;
item.bianji = "确定";
return;
}
if (item.sex == "") {
alert("性别不能为空");
item.edit = true;
item.bianji = "确定";
return;
}
if (item.sex != "男" && item.sex != "女") {
alert("性别按格式填");
item.edit = true;
item.bianji = "确定";
return;
}
return false;
},
},
};
</script>
CSS的样式:
<style>
form {
width: 400px;
height: 200px;
border: 1px solid;
background-color: aquamarine;
padding: 20px;
}
table {
margin-top: 20px;
width: 500px;
border: 1px solid;
background-color: cyan;
}
tr {
text-align: center;
}
th {
border: 1px solid;
}
td {
width: 100px;
border: 1px solid;
background-color: darkorange;
}
tr input {
width: 90px;
}</style>