Vue实现CRUD
Title英雄名称血量{{hero.name}}{{hero.hp}}英雄名称:...
·
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/vue.min.js"></script>
<style type="text/css">
td{
border:1px solid gray;
}
table{
border-collapse:collapse;
}
div#app{
margin:20px auto;
width:400px;
padding:20px;
}
</style>
</head>
<body>
<div id="app">
<table id="heroListTable">
<thead>
<tr>
<th>英雄名称</th>
<th>血量</th>
</tr>
</thead>
<tbody>
<tr v-for="hero in heros ">
<td>{{hero.name}}</td>
<td>{{hero.hp}}</td>
<td>
<a href="#" @click="edit(hero)">编辑</a>
<a href="#" @click="deleteHero(hero.id)">删除</a>
</td>
</tr>
<tr>
<td colspan="3">
英雄名称:<input type="text" v-model="hero4Add.name"/>
<br>
血量:<input type="text" v-model="hero4Add.hp"/>
<br>
<button type="button" v-on:click="add">增加</button>
</td>
</tr>
</tbody>
</table>
<div id="div4Update">
英雄名称:
<input type="text" v-model="hero4Update.name" />
<br>
血量:
<input type="number" v-model="hero4Update.hp" />
<input type="hidden" v-model="hero4Update.id" />
<br>
<button type="button" v-on:click="update">修改</button>
<button type="button" v-on:click="cancel">取消</button>
</div>
</div>
</body>
<script type="text/javascript">
//修改区域隐藏起来先
$("#div4Update").hide();
var data = {
heros: [
{ id: 1, name: '盖伦', hp: 318},
{ id: 2, name: '提莫', hp: 320},
{ id: 3, name: '安妮', hp: 419},
{ id: 4, name: '死歌', hp: 325},
{ id: 5, name: '米波', hp: 422},
],
hero4Add: { id: 0, name: '', hp: '0'},
hero4Update: { id: 0, name: '', hp: '0'}
};
var maxId = 5;
//计算最大值
for (var i = 0;i < data.heros.length; i++){
if(data.heros[i].id > maxId){
maxId = this.heros[i].id;
}
}
var vue = new Vue({
el : '#app',
data : data,
methods : {
add : function(event) {
//获取最大id
maxId++;
//赋予新id
this.hero4Add.id = maxId;
if(this.hero4Add.name.length == 0)
//这里if判断条件不要加{},不然只会新增默认值,不会新增输入的值
this.hero4Add.name = "Hero#" + this.hero4Add.id;
//把对象加入到数组
this.heros.push(this.hero4Add);
//让hero4Add指向新的对象
this.hero4Add = {id : 0,name : '',hp : '0'}
},
deleteHero : function (id) {
//delete是vue的关键字,不能用作方法名
for(var i = 0; i < this.heros.length; i++){
if(this.heros[i].id == id){
this.heros.splice(i, 1);
break;
}
}
},
edit : function (hero) {
$("#heroListTable").hide();
$("#div4Update").show();
this.hero4Update = hero;
},
update : function () {
//因为v-model,已经同步修改了,所以只需要进行恢复显示就行了
$("#heroListTable").show();
$("#div4Update").hide();
},
cancel : function () {
//其实就是恢复显示
$("#heroListTable").show();
$("#div4Update").hide();
}
}
});
</script>
</html>
更多推荐
已为社区贡献1条内容
所有评论(0)