1.传输数据与显示数据不同时,可以使用过滤器改变数据显示格式:wxs
2.封装数据格式函数,在多个js文件引用:js
1.wxs:增强 wxml 标签的表达能力
1)新建文件strFormat.js
var unit = {
reduceMidden: function(text) {
var pinStr = text+'';
var str = text+'';
var length = str.length
if(length<=3){
pinStr = str.substring(0,1)+"*"+str.substring(str.length-1);
}
else if(length>3&&length<12){
pinStr = str.substring(0,1)+"****"+str.substring(str.length-1);
}
else{
pinStr = str.substring(0,1)+"*********"+str.substring(str.length-1);
}
return pinStr;
},
}
module.exports = {
reduceMidden: unit.reduceMidden
}
2)在wxml页面引用过滤器文件
<wxs module="unit" src="../../../utils/strFormat.wxs"></wxs>
3)使用过滤器
<!-- 使用前 -->
<van-field
placeholder="请输入身份证"
value="{{idNumber}}"
></van-field>
<!-- 使用后 -->
<van-field
placeholder="请输入身份证"
value="{{unit.reduceMidden(idNumber)}}"
></van-field>
4)效果
使用前
使用后
2.js:在js文件引用
1)新建文件timeFormat.js
//timestamp 时间戳
//option 格式(年月日 就输入YY-MM-DD 时分 就输入 hh-mm)
//功能如下注释 ↓↓↓↓
const formatDate = (timestamp, option) => {
var date = new Date(timestamp);
var year = date.getFullYear()
var month = date.getMonth() + 1
var day = date.getDate()
var hour = function () {
return date.getHours() < 10 ? '0' + date.getHours() : date.getHours();
}
var minute = function () {
return date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes();
}
var second = function () {
return date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds();
}
//获取 年月日
if (option == 'YY-MM-DD') return " " + year + "-" + month + "-" + day;
//获取年月
if (option == 'YY-MM') return " " + year + "-" + month;
//获取年
if (option == 'YY') return " " + year;
//获取月
if (option == 'MM') return " " + month;
//获取日
if (option == 'DD') return " " + day;
//获取昨天
if (option == 'yesterday') return " " + day - 1;
//获取时分秒
if (option == 'hh-mm-ss') return " " + hour() + ":" + minute() + ":" + second();
//获取时分
if (option == 'hh-mm') return " " + hour() + ":" + minute();
//获取分秒
if (option == 'mm-ss') return minute() + ":" + second();
//获取分
if (option == 'mm') return minute();
//获取秒
if (option == 'ss') return second();
//默认时分秒年月日
return year + '-' + month + '-' + day + ' ' + hour() + ':' + minute() + ":" + second();
}
module.exports = { formatDate }
2)在js页面引用过滤器文件
import timeFormat from "../../../utils/timeFormat";
3)使用过滤器
sourceDateConfirm: function(e){
// 使用前
this.setData({sourceDate : e.detail});
// 使用后
this.setData({sourceDate : timeFormat.formatDate(e.detail, 'YY-MM-DD')});
this.onClose();
},
4)效果
使用前(vant日历组件获取的时间对象)
使用后
参考链接:https://blog.csdn.net/weixin_40967353/article/details/107682345
https://blog.csdn.net/qq_40428678/article/details/90318962