- 要求斑马纹、每一行有查看按钮
- 点击查看,将数据传到父级,父级弹出一个框,显示查看的详情信息,
- 要有时间数据,使用 具名作用域插槽,更改时间格式
- 1.vue.js和时间格式转换工具的引入
<script src="./utils/vue.js"></script>
<!-- vue.js和 时间格式转换工具 -->
<script src="https://unpkg.com/dayjs@1.8.21/dayjs.min.js"></script>
<style>
/* 表格样式 */
.table td {
border: 1px solid rgb(230, 224, 224);
color: rgb(170, 167, 167);
}
.table tr {
text-align: center;
}
.table th {
width: 120px;
height: 20px;
}
/* 斑马条纹 */
.table tr:nth-child(2n) {
background-color: rgb(222, 247, 247);
}
</style>
2.vue组件和插槽
-
<body> <div id="app"> <table-info :info-com="infoList"> <template #date="scope"> <div>{{formatTime(scope.dateInfo)}}</div> </template> </table-info> </div> </body> <template id="table-info"> <div class="table"> <table cellpadding="0" cellspacing="0"> <tr> <th>出生日期</th> <th>姓名</th> <th>地址</th> <th>操作</th> </tr> <!-- 判断是否有数据 --> <!-- 有的情况 --> <template v-if="infoCom.length>0"> <tr v-for="(item,index) in infoCom"> <td> <!-- 具名插槽 --> <slot name="date" :date-info="item.dateInfo"> {{item.dateInfo}} </slot> </td> <td>{{item.name}}</td> <td>{{item.address}}</td> <td><button @click="check(index)">查看</button></td> </tr> </template> <!-- 没有数据的情况 --> <template v-else> <tr> <td colspan="4">暂无数据</td> </tr> </template> </table> </div> </template>
<script> const tableInfo = Vue.component("table-info", { template: `#table-info`, // props传入 props: { infoCom: { type: Array, default: () => ([]) } }, methods: { check(index) { // 通过数组下标去拿数据 alert( "姓名:" + this.infoCom[index].name + '\n' + "地址:" + this.infoCom[index].address + '\n' + "出生日期:" + dayjs(this.infoCom[index].dateInfo).format('YYYY-MM-DD') // 时间格式转换 dayjs已经在script中引入 ) } } }) const app = new Vue({ el: "#app", data() { return { infoList: [ { dateInfo: new Date('2019-2-19').getTime(), // 拿到日期时间戳 name: "张三", address: '三明' }, { dateInfo: new Date('2020-3-12').getTime(), name: " 李四", address: '泉州' }, { dateInfo: new Date('2021-11-23').getTime(), name: "王二", address: '南安' }, { dateInfo: new Date('2022-12-12').getTime(), name: "麻子", address: '福州' } ] } }, computed: { formatTime() { return function (timeStamp) { // 时间戳去转换 return dayjs(timeStamp).format('YYYY-MM-DD') // return dayjs(timeStamp).format('YYYY/MM/DD HH:mm:ss:SSS') } } }, components: { tableInfo }, methods: { } }) </script>
效果图