实现效果:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Vue表单</title>
<style type="text/css">
html,body,div{
width: 100%;
height: 100%;
}
table{
width: 500px;
align-items: center;/* 居中 */
border-collapse: collapse;/* 相邻单元格共享边框 */
}
tr{
height: 30px;
border-bottom: 1px solid #666;
}
</style>
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
</head>
<body>
<div id="app">
<table>
<tr >
<th>编号</th>
<th>姓名</th>
<th>年龄</th>
<th>操作</th>
</tr>
<tr v-for="(stu, index) in stuArr" :key="stu.sid"> <!-- v-for循环遍历数组对象 key相当于数据库索引,当数据改变时只重新加载被改变的数据,节省开销 -->
<th>{{stu.sid}}</th>
<th>{{stu.sname}}</th>
<th>{{stu.sage}}</th>
<th><button @click="del(index)">删除</button></th><!-- "@"是v-on的缩写,用于事件绑定,当事件发生时调用del方法 -->
</tr>
<tr>
<td colspan="4" align="center"><button @click="clr">清空</button></td> <!-- colspan="4" :横向合并4列 -->
</tr>
</table>
<h2>添加学生信息</h2>
姓名:<input type="text" v-model="sname"/><br /> <!-- 与data中的属性值双向绑定 -->
年龄:<input type="text" v-model="sage"/><br />
<button @click="add">添加</button>
</div>
<script>
Vue.createApp({//创建Vue对象
data(){
return{
stuArr:[{//初始化对象数组
sid:1001,
sname:'张三',
sage:21
},
{
sid:1002,
sname:'李四',
sage:21
},
{
sid:1003,
sname:'王五',
sage:21
}
],
sname:'',
sage:0
}
},
methods: {//定义方法
add() {
let stuid=0;
if(this.stuArr.length==0){
stuid=1001;
}else{
stuid=this.stuArr[this.stuArr.length-1].sid+1;
}
let stu={
sid:stuid,
sname:this.sname,
sage:this.sage
}
this.stuArr.push(stu);
},
del(index){
this.stuArr.splice(index,1);
},
clr(){
this.stuArr.splice(0,this.stuArr.length);
}
}
}).mount('#app')//挂载渲染根目录
</script>
</body>
</html>
重难点:
1.v-model
可以在组件上使用以实现双向绑定。(就是页面上的值与Vue对象中的值绑定,同步改变)
等价于
<input
:value="searchText"
@input="searchText = $event.target.value"/>
2.v-for
指令基于一个数组来渲染一个列表。v-for
指令的值需要使用 item in items
形式的特殊语法,其中 items
是源数据的数组,而 item
是迭代项的别名。使用可选的第二个参数表示当前项的位置索引:(item, index) in items
3.:key="循环对象唯一属性",Vue 默认按照“就地更新”的策略来更新通过 v-for
渲染的元素列表。当数据项的顺序改变时,Vue 不会随之移动 DOM 元素的顺序,而是就地更新每个元素,确保它们在原本指定的索引位置上渲染。推荐在任何可行的时候为 v-for
提供一个 key
attribute