需求:
- 把默认数据显示到表格上
- 注意资产超过100的, 都用红色字体标记出来
- 点击删除的a标签, 删除数据;无数据提示
- 实现底部添加资产的功能
注意
- 注意a标签有默认行为-跳转刷新页面(如果有href属性)
- 添加资产时, 提示用户数据不能为空
- form表单里的button的点击事件, 会触发默认表单提交的行为
- 该案例需要下载dayjs和bootstrap
效果图:
代码:
<template>
<div id="app">
<div class="container">
<!-- 顶部搜索框模块 -->
<div class="form-group">
<div class="input-group">
<h4>品牌管理</h4>
</div>
</div>
<!-- 数据表格 -->
<table class="table table-bordered table-hover mt-2">
<thead>
<tr>
<th>编号</th>
<th>资产名称</th>
<th>价格</th>
<th>创建时间</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<!-- v-for渲染数组数据 -->
<tr v-for="(item,idx) in list" :key="item.id">
<td>{{item.id}}</td>
<td>{{item.name}}</td>
<!-- 如果价格超过100,就有red这个类 -->
<!-- <td :class=" item.price>100? 'red':'' ">{{item.price}}</td> -->
<td :class=" {red: item.price>100 } ">{{item.price}}</td>
<td>{{item.time}}</td>
<td><a href="#" @click="delGoods(idx)">删除</a></td>
</tr>
</tbody>
<!-- v-if隐藏提示信息 -->
<tfoot v-if="list.length == 0">
<tr>
<td colspan="5" style="text-align: center">暂无数据</td>
</tr>
</tfoot>
<!-- v-if显示总价和平均价 -->
<tfoot v-if="list.length">
<tr>
<td colspan="5" style="text-align: right">总价:{{getSum}}   平均价:{{getAver}} </td>
</tr>
</tfoot>
</table>
<!-- 添加资产 -->
<form class="form-inline">
<div class="form-group">
<div class="input-group">
<input type="text" class="form-control" v-model="good.name" placeholder="资产名称" />
</div>
</div>
<div class="form-group">
<div class="input-group">
<!-- v-model修饰符 number转为数字类型 -->
<input type="text" class="form-control" v-model.number="good.price" placeholder="价格" />
</div>
</div>
<!-- 修饰符prevent阻止表单提交 -->
<button class="btn btn-primary" @click.prevent="addGoods">添加资产</button>
</form>
</div>
</div>
</template>
<script>
import dayjs from "dayjs"
import "bootstrap/dist/css/bootstrap.css"
export default {
data() {
return {
good: {
name: "", // 名称
price: "", // 价格
},
list: [
{ id: 100, name: "外套", price: 199, time: dayjs(new Date('2010-08-12')).format('YYYY-MM-DD') },
{ id: 101, name: "裤子", price: 34, time: dayjs(new Date('2013-09-01')).format('YYYY-MM-DD') },
{ id: 102, name: "鞋", price: 25.4, time: dayjs(new Date('2018-11-22')).format('YYYY-MM-DD') },
{ id: 103, name: "头发", price: 19900, time: dayjs(new Date('2020-12-12')).format('YYYY-MM-DD') }
],
};
},
methods: {
delGoods(idx) {
this.list.splice(idx, 1)
},
addGoods() {
// 优化:变量解构赋值
const { list, good } = this
// 1.判断数组长度,取不同的id值
const id = list.length > 0 ? list[list.length - 1].id + 1 : 100
// 2.非空判断
if (good.name == "" || good.price == "") return alert('请输入正确的值!')
let obj = {
id,
name: good.name,
price: good.price,
time: dayjs(new Date()).format('YYYY-MM-DD')
}
list.push(obj)
//3. 清空表单内容
good.name = '',
good.price = ''
}
},
// 涉及计算的操作用到computed,一定要有返回值
computed: {
getSum() {
// 数组求和reduce
let sum = this.list.reduce((sum, item) => sum + item.price, 0)
// 保留两位小数
return sum.toFixed(2)
},
getAver() {
let average = this.getSum / this.list.length
return average.toFixed(2)
}
}
};
</script>
<style>
.red {
color: red;
}
</style>