上篇是数据返回全部消息,为数组时,本篇是接口每次只返回一条消息,并且 每天弹过的消息只弹一次。
每日只弹一次:传参数的时候需要把msgid拼接到一起,所以把每条已经弹过的msgId和当天的时间储存到本地,在调接口之前,先取出已有 的id,如果已经有id就拼接
/**
* 获取接口消息
*/
getMsgData() {
this.$u.api.msg.getNotifyMsg({
receiveStatus: 0,
excludeMsgIds: this.getCacheMsgIds(),
isQueryCount: 1,
}).then(res => {
uni.hideToast();
if (res && res != true) {
this.msgList = res
this.msgId = this.msgList.notifyMsgInfo.msgId;
this.notifyObjectId = this.msgList.notifyMsgInfo.notifyObjectId;
this.count = this.msgList.count ? this.msgList.count : 0;
// 緩存消息主鍵
this.cacheMsgIds(); // 拿到当前的消息数据,把msgid缓存
this.show = true;
}
})
},
/**
* 缓存当日的消息id
*/
cacheMsgIds() {
if (this.msgId != '') {
// 取出已有的緩存id
let excludeMsgIds = this.getCacheMsgIds(); // 取出已有的id
if (this.$pop.isEmpty(excludeMsgIds)) { // 如果id为空的时候 isEmpty是封装的判断str是否为空方法 为空的时候返回true 反则为false
excludeMsgIds = this.msgId; // 如果为空的时候 就把接口获取的msgId给excludeMsgIds
} else { // 已有的id
if (excludeMsgIds.indexOf(this.msgId) < 0) { // indexOf() 方法可返回某个指定的字符串值在字符串中首次出现的位置。
excludeMsgIds += ',' + this.msgId; // 拼接id 例:'14526895645','5668742554'
}
}
let date = this.$pop.getCurrentTime('date'); // 获取当前时间 getCurrentTime是封装的获取当前时间的方法
uni.setStorageSync(date + "-EXCLUDEMSGIDS", excludeMsgIds); // 缓存当天的日期和当前已看过消息的id
this.excludeMsgIds = excludeMsgIds;
}
},
/**
* 获取当日缓存的消息id
*/
getCacheMsgIds() {
if (this.excludeMsgIds == '') {
let date = this.$pop.getCurrentTime('date');
this.excludeMsgIds = uni.getStorageSync(date + "-EXCLUDEMSGIDS", '');
}
return this.excludeMsgIds;
},
在弹窗关闭的时候,也要缓存当日的消息id
<u-popup v-model="show" mode="bottom" border-radius="50" @close="cacheMsgIds()">
</u-popup>
isEmpty方法:
isEmpty(val) {
if (val === "" || val === undefined || val === null || val.length == 0) {
return true;
}
return false;
},
getCurrentTime方法:
/**
* 创建时间(取当前时间)
* @returns {string}
*/
getCurrentTime(type) {
//获取当前时间并打印
let yy = new Date().getFullYear();
let mm = new Date().getMonth() + 1;
let dd = new Date().getDate();
let hh = new Date().getHours();
let mf = new Date().getMinutes() < 10 ? '0' + new Date().getMinutes() : new Date().getMinutes();
let ss = new Date().getSeconds() < 10 ? '0' + new Date().getSeconds() : new Date().getSeconds();
var gettime = ''
if (type == 'yy') {
gettime = yy;
} else if (type == 'month') {
gettime = mm;
} else if (type == 'date') {
gettime = yy + '-' + mm + '-' + dd;
} else {
gettime = dd;
}
return gettime
},