实现一个简单用户添加查找删除的vue小案例
效果
![]()
代码
html部分
<div class="add">
用户编号:
<input type="text" v-model="userId" ref="inputId"> 用户姓名:
<input type="text" v-model="userName" @keydown.enter="addUserData">
<button @click="addUserData">添加</button>
<p v-if="show">编号或姓名不能为空</p>
</div>
<div class="add">
用户姓名:
<input type="text" placeholder="请输入搜索条件" v-model="searchValue" >
</div>
<div>
<table class="tb">
<tr>
<th>编号</th>
<th>用户名</th>
<th>添加时间</th>
<th>操作</th>
</tr>
<tr v-for="(item,index) in newList" :key="item.id" >
<td>{{item.id}}</td>
<td>{{item.userName}}</td>
<td>{{item.addDateTime|showDate}}</td>
<td>
<a href="#" @click='deleteUserData(index)'>删除</a>
</td>
</tr>
<tr v-if="userList.length===0">
<td colspan="4">没有用户数据</td>
</tr>
</table>
</div>
</div>
js部分
// 时间过滤器
Vue.filter('showDate', function (time, sep) {
// 年-月-日
var year = time.getFullYear();
var m = time.getMonth() + 1;
var d = time.getDate();
return year + "-" + m + "-" + d
})
var vm = new Vue({
el: "#app",
data: {
trShow: true,
show: false,
userId: null,
userName: '',
searchValue: '', //表示搜索的数据
userList: [{
id: 1,
userName: '张三',
addDateTime: new Date()
}, {
id: 2,
userName: '李四',
addDateTime: new Date()
}, {
id: 3,
userName: '王五',
addDateTime: new Date()
}]
},
methods: {
fn() {
console.log(5);
this.trShow = false;
},
// 删除操作
deleteUserData(i) {
this.userList.splice(i, 1)
},
// 添加操作
addUserData() {
if (this.userId == null || this.userName == null) {
this.show = true;
return
}
this.show = false;
this.userList.push({
id: this.userId,
userName: this.userName,
addDateTime: new Date()
})
this.userId = null;
this.userName = '';
}
},
mounted() {
this.$refs.inputId.focus();
},
computed: {
// 完成用户信息的搜索
newList() {
var arr = this.userList.filter(value => value.userName.indexOf(this.searchValue) !== -1)
return arr
}
}
})
css部分
#app {
width: 600px;
margin: 10px auto;
}
.tb {
/* 合并边框 */
border-collapse: collapse;
width: 100%;
}
.tb th {
background-color: darkturquoise;
color: white;
}
.tb td,
.tb th {
padding: 5px;
border: 1px solid #999999;
text-align: center;
}
.add {
padding: 5px;
border: 1px solid #999999;
margin-bottom: 10px;
}
.add p {
margin: 0;
color: red;
}