Vuejs小案例
案例视图:
涉及到的Vue相关思想
v-if
和v-else
进行条件判断
v-for
如何遍历数组
v-on
绑定点击事件
computed
计算属性
methods
方法
filters
过滤器
.splice(下标,删除的个数)
数组方法
v-model
的使用
watch
监听data
中数据的变化
案例代码(实现相应的功能需求):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
table {
width: 800px;
border-spacing: 0;
margin: 20px auto;
}
th,
td {
border: 1px solid #ededed;
height: 40px;
text-align: center;
min-width: 50px;
}
th {
background: #f6f6f6;
}
button {
width: 60px;
height: 30px;
font-weight: 700;
}
.priceBtn {
background: white;
border: 1px solid #f3f3f3;
}
.delBtn {
background: red;
border: 0;
color: white;
}
</style>
</head>
<body>
<div id="app">
<table>
<thead>
<tr>
<th>
<input
type="checkbox"
@click="handleSelectClick"
v-model="isChecked"
/>
</th>
<th></th>
<th>书籍名称</th>
<th>出版日期</th>
<th>价格</th>
<th>购买数量</th>
<th>操作</th>
</tr>
</thead>
<tbody v-if="books.length">
<tr v-for="(item,index) in books" :key="item.id">
<td>
<input type="checkbox" :value="item.id" v-model="ids" />
</td>
<td>{
{item.id}}</td>
<td>{
{item.name}}</td>
<td>{
{item.date}}</td>
<td>{
{item.price|showPrice}}</td>
<td>
<button class="priceBtn" @click="handleNumDecrementClick(index)">
-
</button>
{
{item.num}}
<button class="priceBtn" @click="handleNumIncrementClick(index)">
+
</button>
</td>
<td>
<button class="delBtn" @click="handleDeleClick(index)">
移除
</button>
</td>
</tr>
</tbody>
<tbody v-else>
<tr>
<td colspan="7">没有图书。。。</td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="7" style="text-align: left">
总价:{
{totalPrice|showPrice}} {
{ids}}
</td>
</tr>
</tfoot>
</table>
</div>
</body>
<script src="../vue.js"></script>
<script>
const app = new Vue({
el: "#app",
data: {
books: [
{
id: 1, name: "《算法导论》", date: "2006-9", price: 85, num: 1 },
{
id: 2,
name: "《UNIX编程艺术》",
date: "2006-2",
price: 59,
num: 1,
},
{
id: 3, name: "《编辑珠玑》", date: "2008-10", price: 39, num: 1 },
{
id: 4, name: "《代码大全》", date: "2006-3", price: 128, num: 1 },
],
ids: [],
isChecked: false,
},
computed: {
totalPrice() {
return this.books.reduce(
(pre, current) => pre + current.price * current.num,
0
);
},
},
methods: {
handleNumDecrementClick(index) {
if (this.books[index].num <= 1) {
this.handleDeleClick(index);
} else {
this.books[index].num--;
}
},
handleNumIncrementClick(index) {
this.books[index].num++;
},
handleDeleClick(index) {
this.books.splice(index, 1);
},
handleSelectClick(event) {
if (event.target.checked) {
this.ids = this.books.map((item) => item.id);
} else {
this.ids = [];
}
},
},
filters: {
showPrice(price) {
return "¥" + price.toFixed(2);
},
},
watch: {
ids(newValue, oldValue) {
this.isChecked = newValue.length === this.books.length;
},
},
});
</script>
</html>