<style>
* {
margin: 0;
padding: 0;
}
[v-cloak] {
display: none;
}
.headBar {
width: 500px;
height: 40px;
line-height: 40px;
margin: 100px auto 0;
text-align: center;
background-color: pink;
}
input {
outline: 0;
}
table {
border: 1px solid #444;
margin: 0 auto;
width: 500px;
border-collapse: collapse;
}
th {
font-weight: normal;
}
thead {
background-color: pink;
}
thead th {
height: 40px;
font-weight: bold;
}
tbody th {
height: 30px;
border: 1px solid #444;
}
a {
text-decoration: none;
}
</style>
<script src="../vue.js"></script>
<script>
var vm = new Vue({
el: '.app',
data: {
flag: false,
id: '',
name: '',
books: [{
id: 1,
name: '西游记',
data: ''
}, {
id: 2,
name: '三国演义',
data: ''
}, {
id: 3,
name: '水浒传',
data: ''
}]
},
methods: {
add: function() {
if (this.flag) {
this.books.some((item) => {
if (item.id == this.id) {
item.name = this.name;
return true;
}
});
this.flag = false;
} else {
var book = {};
book.id = this.id;
book.name = this.name;
book.data = '';
this.books.push(book);
}
this.id = '';
this.name = '';
},
toEdit: function(id) {
this.flag = true;
console.log(id);
var book = this.books.filter(function(item) {
return item.id == id;
})
console.log(book);
this.id = book[0].id;
this.name = book[0].name;
},
del: function(id) {
// this.books = this.books.filter(function(item) {
// return item.id != id;
// })
var index = this.books.findIndex(function(item) {
return item.id == id;
})
this.books.splice(index, 1);
}
},
})
<script>
<body>
<div class="app" v-cloak>
<div class="sapp">
<div class="headBar">
<form action="#">
<label for="id">编号:</label>
<input type="text" id="id" v-model="id" :disabled="flag">
<label for="name">名称:</label>
<input type="text" id="name" v-model="name">
<input type="submit" value="提交" @click="add">
</form>
</div>
<table>
<thead>
<tr>
<th>编号</th>
<th>名称</th>
<th>时间</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr v-for="(item, index) in books" :key="books.id">
<th>{{item.id}}</th>
<th>{{item.name}}</th>
<th>{{item.data}}</th>
<th><a href="" @click.prevent="toEdit(item.id)">修改</a>
<span>|</span>
<a href="" @click.prevent="del(item.id)">删除</a></th>
</tr>
</tbody>
</table>
</div>
</div>
</body>