本文以时间格式化为例,后端API接口常常返回给前端的是一个int时间戳,前端需要在显示的时候转换成2019-06-28格式。
首先在/libs/目录下新建common.js,并写入如下内容:
let util = {};
util.formatDate = function (date, fmt) {
if (/(y+)/.test(fmt)) {
fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
}
let o = {
'M+': date.getMonth() + 1,
'd+': date.getDate(),
'h+': date.getHours(),
'm+': date.getMinutes(),
's+': date.getSeconds()
};
for (let k in o) {
if (new RegExp(`(${k})`).test(fmt)) {
let str = o[k] + '';
fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? str : util.padLeftZero(str));
}
}
return fmt;
};
util.padLeftZero = function (str) {
return ('00' + str).substr(str.length);
};
export default util;
然后在业务页面比如lists.vue里如下图所示调用:
<template>
<view>
<view class="kx-list">
<view
class="item"
:key="key"
v-for="(item, key) in kx_list">
<text class="title">
{{item.post_time| formatTime}}
</text>
</view>
</view>
</view>
</template>
<script>
import common from '@/libs/common.js'
export default {
data() {
return {
kx_list: {
}
}
},
filters: {
formatTime(time) {
var date = new Date(time);
return common.formatDate(date, 'yyyy-MM-dd hh:mm');
}
}
</script>
最终页面就会显示2019-06-28 12:00格式的时间,同理当我们需要给订单的状态1,2,3,4,5
等变量显示为待付款,待发货,待收货,待评价时也可以参考上面这样使用。
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有