<script src='vue.js'></script>
<script>
new Vue({
el: '#myApp',
data: {
selectIndex:"",
name: "",
sex: "",
tel: "",
hobbies: ["打王者", "篮球", "看动漫", "敲代码", "看帅哥", "卖萌"],//爱好列表
hobbiesSelect: [],//选中对象的爱好列表
student: [
{
name: "打打打",
tel: "1234567",
sex: "男",
hobbies: ["打王者"]
},
{
name: "呜呜呜",
tel: "1234567",
sex: "男",
hobbies: ["打王者","篮球"]
},
{
name: "碳酸钙",
tel: "1234567",
sex: "女",
hobbies: ["打王者","带娃"]
}
]
},
methods: {
del(i) {
var isSure = confirm("要确定删除吗?")
if (isSure) {
this.student.splice(i, 1)
}
},
update(s, a) {
// 1 取出要修改的数据源 给input双向绑定数据进行赋值
this.name = s.name
this.tel = s.tel
this.sex = s.sex
this.hobbiesSelect = s.hobbies
this.selectIndex=a //点击修改 selectIndex 就是修改的索引,不点击修改,selectIndex=""
},
addOrUpdate(){
// 1 添加功能 就是向数组里面添加元素,组织一个对象添加进去
let {name,tel,sex,hobbiesSelect}=this //对象解构 按需引入,
let data={
name:name,
tel:tel,
sex:sex,
hobbies:hobbiesSelect
}
if(this.selectIndex!==""){
var isSure=confirm("是否要修改?")
if(isSure){
// splice() 根据参数个数不同,功能也不一样,多态
// 删除当前this.selectIndex索引值的元素,添加一个新的元素
this.student.splice(this.selectIndex,1,data)
}
this.selectIndex=""
}else{
this.student.push(data)
}
}
}
})
</script>
HTML:
<div id='myApp'>
<table border="1">
<thead>
<tr>
<th>姓名</th>
<th>手机</th>
<th>性别</th>
<th>爱好</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<!--
v-for和v-if尽量不用使用在同一个标签上
vue2:v-for的优先级比 v-if的优先级要高,先进行循环,在进行判断,所以循环的次数没有减少
vue3:v-if的优先级要高于v-for,先执行v-if,在进行循环渲染,所以条件没成立,循环直接不走了,可以减少循环次数,提升页面渲染性能
-->
<template v-if="student.length>0">
<tr v-for="(s,i) in student">
<td>{{s.name}}</td>
<td>{{s.tel}}</td>
<td>{{s.sex}}</td>
<td>{{s.hobbies.join(",")}}</td>
<td>
<button @click="del(i)">删除</button>
<button @click="update(s,i)">修改</button>
</td>
</tr>
</template>
<tr v-else>
<td colspan="5">未查询到数据源</td>
</tr>
</tbody>
</table>
<hr>
<input type="text" v-model="name" placeholder="请输入大名">
<input type="text" v-model="tel" placeholder="请输入手机号">
<input type="radio" v-model="sex" value="男">男
<input type="radio" v-model="sex" value="女">女
<br>
<label v-for="h,i in hobbies">
<input type="checkbox" v-model="hobbiesSelect" :value="h">{{h}}
</label>
<button @click="addOrUpdate">{{selectIndex!=="" ? '修改':"添加"}}</button>
</div>
css样式:
table {
width: 100%;
text-align: center;
border-collapse: collapse;
}
tbody tr:nth-child(odd) {
background-color: gray;
}
td {
height: 30px;
}