- 只是为了写demo,所以为了方便起见,所有文件写在了一起,所以见谅
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
<title>Document</title>
<script src="./lib/vue.js"></script>
<style>
table {
margin: 50px auto;
width: 60%;
border: 1px solid red;
border-collapse: collapse;
/*关键代码*/
background-color: #ccc;
}
th {
text-align: center;
border: 1px solid #e9faff;
}
td {
text-align: center;
border: 1px solid #e9faff;
background-color: pink;
}
</style>
</head>
<body>
<div id='app'>
<table>
<thead>
<tr>
<th>ID</th>
<th>商品名</th>
<th>生产日期</th>
<th>售价</th>
<th>数量</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr v-for="(item,index) in book" :key="item.id">
<td>{{ item.id }}</td>
<td>{{ item.name }}</td>
<td>{{ item.data }}</td>
<td>{{ item.price | money}}</td>
<td>
<button @click="decremet(index)">-</button>
{{ item.num }}
<button @click="incremet(index)">+</button>
</td>
<td>
<button @click="del(index)">删除</button>
</td>
</tr>
<tr>
<td colspan="6" style="text-align:left">总价格:{{ add | money }}</td>
</tr>
</tbody>
</table>
</div>
<script>
var vm = new Vue({
el: '#app',
data: {
book: [{
id: 1,
name: '雷霆咆哮',
data: '2020/03/10',
price: '6300',
num: 1
},
{
id: 2,
name: '沙漠死神',
data: '1990/06/19',
price: '3150',
num: 1
},
{
id: 3,
name: '蛮族之王',
data: '2000/12/5',
price: '1350',
num: 1
},
{
id: 4,
name: '盖伦',
price: '3150',
data: '1997/05/20',
num: 1
},
{
id: 5,
name: '诺手',
price: '6300',
data: '1920/08/29',
num: 1
}
]
},
methods: {
incremet(index) {
this.book[index].num++
},
decremet(index) {
if (this.book[index].num < 2) {
return
}
this.book[index].num--
},
del(index){
this.book.splice(index,1)
}
},
filters: {
money: function (a) {
return '¥' + Number(a).toFixed(2)
}
},
computed: {
add() {
let end = 0;
for (let i = 0; i < this.book.length; i++) {
end += this.book[i].price * this.book[i].num
}
return end
}
}
})
</script>
</body>
</html>
1.表格结构
<table>
<thead>
<tr>
<th>ID</th>
<th>商品名</th>
</tr>
</thead>
<tbody>
<tr>
<td>{{ item.id }}</td>
<td>{{ item.name }}</td>
<td>{{ item.data }}</td>
</tr>
</tbody>
</table>
2.表格合并边框
border-collapse: collapse;
3.局部过滤器写法
filters: {
money: function (a) {
return '¥' + Number(a).toFixed(2)
}
},
4.计算属性的写法
computed: {
add() {
let end = 0;
for (let i = 0; i < this.book.length; i++) {
end += this.book[i].price * this.book[i].num
}
return end
}
}
5. toFixed()
- toFixed() 方法可把 Number 四舍五入为指定小数位数的数字
- Vue中使用toFixed()报错,说toFixed不是一个函数
- 给数据转一下数据类型 Number
Number(a).toFixed(2)








网友评论