IM部分处理

This commit is contained in:
abu 2025-04-30 14:28:07 +08:00
parent eaa9f50e7a
commit 192f493535
22 changed files with 2957 additions and 2398 deletions

16
App.vue
View File

@ -11,8 +11,14 @@ import provinceList from './json/area_province.js';
import cityList from './json/area_city.js'; import cityList from './json/area_city.js';
import districtList from './json/area_district.js'; import districtList from './json/area_district.js';
import storage from '@/utils/storage.js'; // import storage from '@/utils/storage.js'; //
//im
import { TUIChatKit } from '@/TUIKit';
import { loginIm } from '@/utils/handleim.js';
export default { export default {
//
globalData: {
chat: null
},
data() { data() {
return { return {
config config
@ -56,6 +62,14 @@ export default {
plus.globalEvent.addEventListener('newintent', (e) => { plus.globalEvent.addEventListener('newintent', (e) => {
this.checkArguments(); // this.checkArguments(); //
}); });
// init im
var ddd = TUIChatKit.init();
console.log('dasjdlasjdlajsldjaslkdjasljdklasdljasldadjaldjlkasdlkasjdalsdjl', ddd);
//
console.log('是否登录', storage.getHasLogin());
if (storage.getHasLogin()) {
loginIm();
}
// #endif // #endif
// #ifdef MP-WEIXIN // #ifdef MP-WEIXIN

View File

@ -1,85 +1,103 @@
<template> <template>
<div class="custom"> <div class="custom">
<template v-if="customData.businessID === CHAT_MSG_CUSTOM_TYPE.SERVICE"> <template v-if="customData.businessID === CHAT_MSG_CUSTOM_TYPE.SERVICE">
<div> <div>
<h1> <h1>
<label>{{ extension.title }}</label> <label>{{ extension.title }}</label>
<a <a
v-if="extension.hyperlinks_text" v-if="extension.hyperlinks_text"
:href="extension.hyperlinks_text.value" :href="extension.hyperlinks_text.value"
target="view_window" target="view_window"
>{{ extension.hyperlinks_text.key }}</a> >
</h1> {{ extension.hyperlinks_text.key }}
<ul v-if="extension.item && extension.item.length > 0"> </a>
<li </h1>
v-for="(item, index) in extension.item" <ul v-if="extension.item && extension.item.length > 0">
:key="index" <li
> v-for="(item, index) in extension.item"
<a :key="index"
v-if="isUrl(item.value)" >
:href="item.value" <a
target="view_window" v-if="isUrl(item.value)"
>{{ item.key }}</a> :href="item.value"
<p v-else> target="view_window"
{{ item.key }} >
</p> {{ item.key }}
</li> </a>
</ul> <p v-else>
<article>{{ extension.description }}</article> {{ item.key }}
</div> </p>
</template> </li>
<template v-else-if="customData.businessID === CHAT_MSG_CUSTOM_TYPE.EVALUATE"> </ul>
<div class="evaluate"> <article>{{ extension.description }}</article>
<h1>{{ TUITranslateService.t("message.custom.对本次服务评价") }}</h1> </div>
<ul class="evaluate-list"> </template>
<li <template v-else-if="customData.businessID === CHAT_MSG_CUSTOM_TYPE.EVALUATE">
v-for="(item, index) in Math.max(customData.score, 0)" <div class="evaluate">
:key="index" <h1>{{ TUITranslateService.t('message.custom.对本次服务评价') }}</h1>
class="evaluate-list-item" <ul class="evaluate-list">
> <li
<Icon v-for="(item, index) in Math.max(customData.score, 0)"
:file="star" :key="index"
class="file-icon" class="evaluate-list-item"
/> >
</li> <Icon
</ul> :file="star"
<article>{{ customData.comment }}</article> class="file-icon"
</div> />
</template> </li>
<template v-else-if="customData.businessID === CHAT_MSG_CUSTOM_TYPE.ORDER"> </ul>
<div <article>{{ customData.comment }}</article>
class="order" </div>
@click="openLink(customData.link)" </template>
> <!-- 自定义视频消息 -->
<img <template v-else-if="customData.businessID === 'video'">
:src="customData.imageUrl" <div
> class="order"
<main> @click="openRouter(customData.link)"
<h1>{{ customData.title }}</h1> >
<p>{{ customData.description }}</p> <img :src="customData.imageUrl" />
<span>{{ customData.price }}</span> <main>
</main> <h1>{{ customData.title }}</h1>
</div> <p>{{ customData.description }}</p>
</template> <span>{{ customData.price }}</span>
<template v-else-if="customData.businessID === CHAT_MSG_CUSTOM_TYPE.LINK"> </main>
<div class="textLink"> </div>
<p>{{ customData.text }}</p> </template>
<a
:href="customData.link" <template v-else-if="customData.businessID === CHAT_MSG_CUSTOM_TYPE.ORDER">
target="view_window" <div
>{{ class="order"
TUITranslateService.t("message.custom.查看详情>>") @click="openLink(customData.link)"
}}</a> >
</div> <img :src="customData.imageUrl" />
</template> <main>
<template v-else> <h1>{{ customData.title }}</h1>
<span v-html="content.custom" /> <p>{{ customData.description }}</p>
</template> <span>{{ customData.price }}</span>
</div> </main>
</div>
</template>
<template v-else-if="customData.businessID === CHAT_MSG_CUSTOM_TYPE.LINK">
<div class="textLink">
<p>{{ customData.text }}</p>
<a
:href="customData.link"
target="view_window"
>
{{ TUITranslateService.t('message.custom.查看详情>>') }}
</a>
</div>
</template>
<template v-else>
<span v-html="content.custom" />
</template>
</div>
</template> </template>
<script lang="ts" setup> <script lang="ts" setup>
import { watchEffect, ref } from '../../../../adapter-vue'; import { watchEffect, ref } from '../../../../adapter-vue';
import { TUIGlobal } from '@tencentcloud/universal-api';
import { TUITranslateService, IMessageModel } from '@tencentcloud/chat-uikit-engine'; import { TUITranslateService, IMessageModel } from '@tencentcloud/chat-uikit-engine';
import { isUrl, JSONToObject } from '../../../../utils/index'; import { isUrl, JSONToObject } from '../../../../utils/index';
import { CHAT_MSG_CUSTOM_TYPE } from '../../../../constant'; import { CHAT_MSG_CUSTOM_TYPE } from '../../../../constant';
@ -87,101 +105,106 @@ import { ICustomMessagePayload } from '../../../../interface';
import Icon from '../../../common/Icon.vue'; import Icon from '../../../common/Icon.vue';
import star from '../../../../assets/icon/star-light.png'; import star from '../../../../assets/icon/star-light.png';
interface Props { interface Props {
messageItem: IMessageModel; messageItem: IMessageModel;
content: any; content: any;
} }
const props = withDefaults(defineProps<Props>(), { const props = withDefaults(defineProps<Props>(), {
messageItem: undefined, messageItem: undefined,
content: undefined, content: undefined
}); });
const custom = ref(); const custom = ref();
const message = ref<IMessageModel>(); const message = ref<IMessageModel>();
const extension = ref(); const extension = ref();
const customData = ref<ICustomMessagePayload>({ const customData = ref<ICustomMessagePayload>({
businessID: '', businessID: ''
}); });
watchEffect(() => { watchEffect(() => {
custom.value = props.content; custom.value = props.content;
message.value = props.messageItem; message.value = props.messageItem;
const { payload } = props.messageItem; const { payload } = props.messageItem;
customData.value = payload.data || ''; customData.value = payload.data || '';
customData.value = JSONToObject(payload.data); customData.value = JSONToObject(payload.data);
if (payload.data === CHAT_MSG_CUSTOM_TYPE.SERVICE) { if (payload.data === CHAT_MSG_CUSTOM_TYPE.SERVICE) {
extension.value = JSONToObject(payload.extension); extension.value = JSONToObject(payload.extension);
} }
}); });
const openLink = (url: any) => { const openLink = (url: any) => {
window.open(url); window.open(url);
};
const openRouter = (url: any) => {
TUIGlobal.navigateTo({
url
});
}; };
</script> </script>
<style lang="scss" scoped> <style lang="scss" scoped>
@import "../../../../assets/styles/common"; @import '../../../../assets/styles/common';
a { a {
color: #679ce1; color: #679ce1;
} }
.custom { .custom {
font-size: 14px; font-size: 14px;
h1 { h1 {
font-size: 14px; font-size: 14px;
color: #000; color: #000;
} }
h1, h1,
a, a,
p { p {
font-size: 14px; font-size: 14px;
} }
.evaluate { .evaluate {
ul { ul {
display: flex; display: flex;
padding: 10px 0; padding: 10px 0;
} }
&-list { &-list {
display: flex; display: flex;
flex-direction: row; flex-direction: row;
&-item { &-item {
padding: 0 2px; padding: 0 2px;
} }
} }
} }
.order { .order {
display: flex; display: flex;
main { main {
padding-left: 5px; padding-left: 5px;
p { p {
font-family: PingFangSC-Regular; font-family: PingFangSC-Regular;
width: 145px; width: 145px;
line-height: 17px; line-height: 17px;
font-size: 14px; font-size: 14px;
color: #999; color: #999;
letter-spacing: 0; letter-spacing: 0;
margin-bottom: 6px; margin-bottom: 6px;
word-break: break-word; word-break: break-word;
} }
span { span {
font-family: PingFangSC-Regular; font-family: PingFangSC-Regular;
line-height: 25px; line-height: 25px;
color: #ff7201; color: #ff7201;
} }
} }
img { img {
width: 67px; width: 67px;
height: 67px; height: 67px;
} }
} }
} }
</style> </style>

View File

@ -1,123 +1,108 @@
<template> <template>
<div <div
ref="conversationListInnerDomRef" ref="conversationListInnerDomRef"
class="tui-conversation-list" class="tui-conversation-list"
> >
<ActionsMenu <ActionsMenu
v-if="isShowOverlay" v-if="isShowOverlay"
:selectedConversation="currentConversation" :selectedConversation="currentConversation"
:actionsMenuPosition="actionsMenuPosition" :actionsMenuPosition="actionsMenuPosition"
:selectedConversationDomRect="currentConversationDomRect" :selectedConversationDomRect="currentConversationDomRect"
@closeConversationActionMenu="closeConversationActionMenu" @closeConversationActionMenu="closeConversationActionMenu"
/> />
<div <div
v-for="(conversation, index) in conversationList" v-for="(conversation, index) in conversationList"
:id="`convlistitem-${index}`" :id="`convlistitem-${index}`"
:key="index" :key="index"
:class="[ :class="['tui-conversation-content', isMobile && 'tui-conversation-content-h5 disable-select']"
'tui-conversation-content', >
isMobile && 'tui-conversation-content-h5 disable-select', <div
]" :class="[
> isPC && 'isPC',
<div 'tui-conversation-item',
:class="[ currentConversationID === conversation.conversationID && 'tui-conversation-item-selected',
isPC && 'isPC', conversation.isPinned && 'tui-conversation-item-pinned'
'tui-conversation-item', ]"
currentConversationID === conversation.conversationID && @click="enterConversationChat(conversation.conversationID)"
'tui-conversation-item-selected', @longpress="showConversationActionMenu($event, conversation, index)"
conversation.isPinned && 'tui-conversation-item-pinned', @contextmenu="showConversationActionMenu($event, conversation, index, true)"
]" >
@click="enterConversationChat(conversation.conversationID)" <aside class="left">
@longpress="showConversationActionMenu($event, conversation, index)" <Avatar
@contextmenu="showConversationActionMenu($event, conversation, index, true)" useSkeletonAnimation
> :url="conversation.getAvatar()"
<aside class="left"> size="30px"
<Avatar />
useSkeletonAnimation <div
:url="conversation.getAvatar()" v-if="userOnlineStatusMap && isShowUserOnlineStatus(conversation)"
size="30px" :class="[
/> 'online-status',
<div Object.keys(userOnlineStatusMap).length > 0 &&
v-if="userOnlineStatusMap && isShowUserOnlineStatus(conversation)" Object.keys(userOnlineStatusMap).includes(conversation.userProfile.userID) &&
:class="[ userOnlineStatusMap[conversation.userProfile.userID].statusType === 1
'online-status', ? 'online-status-online'
Object.keys(userOnlineStatusMap).length > 0 && : 'online-status-offline'
Object.keys(userOnlineStatusMap).includes( ]"
conversation.userProfile.userID />
) && <span
userOnlineStatusMap[conversation.userProfile.userID] v-if="conversation.unreadCount > 0 && !conversation.isMuted"
.statusType === 1 class="num"
? 'online-status-online' >
: 'online-status-offline', {{ conversation.unreadCount > 99 ? '99+' : conversation.unreadCount }}
]" </span>
/> <span
<span v-if="conversation.unreadCount > 0 && conversation.isMuted"
v-if="conversation.unreadCount > 0 && !conversation.isMuted" class="num-notify"
class="num" />
> </aside>
{{ <div class="content">
conversation.unreadCount > 99 ? "99+" : conversation.unreadCount <div class="content-header">
}} <label class="content-header-label">
</span> <p class="name">{{ conversation.getShowName() }}</p>
<span </label>
v-if="conversation.unreadCount > 0 && conversation.isMuted" <div class="middle-box">
class="num-notify" <span
/> v-if="conversation.draftText && conversation.conversationID !== currentConversationID"
</aside> class="middle-box-draft"
<div class="content"> >
<div class="content-header"> {{ TUITranslateService.t('TUIChat.[草稿]') }}
<label class="content-header-label"> </span>
<p class="name">{{ conversation.getShowName() }}</p> <span
</label> v-else-if="conversation.type === 'GROUP' && conversation.groupAtInfoList && conversation.groupAtInfoList.length > 0"
<div class="middle-box"> class="middle-box-at"
<span >
v-if="conversation.draftText && conversation.conversationID !== currentConversationID" {{ conversation.getGroupAtInfo() }}
class="middle-box-draft" </span>
>{{ TUITranslateService.t('TUIChat.[草稿]') }}</span> <div class="middle-box-content">
<span {{ conversation.getLastMessage('text') }}
v-else-if=" </div>
conversation.type === 'GROUP' && </div>
conversation.groupAtInfoList && </div>
conversation.groupAtInfoList.length > 0 <div class="content-footer">
" <span class="time">{{ conversation.getLastMessage('time') }}</span>
class="middle-box-at" <Icon
>{{ conversation.getGroupAtInfo() }}</span> v-if="conversation.isMuted"
<div class="middle-box-content"> :file="muteIcon"
{{ conversation.getLastMessage("text") }} />
</div> </div>
</div> </div>
</div> </div>
<div class="content-footer"> </div>
<span class="time">{{ conversation.getLastMessage("time") }}</span> </div>
<Icon
v-if="conversation.isMuted"
:file="muteIcon"
/>
</div>
</div>
</div>
</div>
</div>
</template> </template>
<script lang="ts" setup> <script lang="ts" setup>
interface IUserStatus { interface IUserStatus {
statusType: number; statusType: number;
customStatus: string; customStatus: string;
} }
interface IUserStatusMap { interface IUserStatusMap {
[userID: string]: IUserStatus; [userID: string]: IUserStatus;
} }
import { ref, onMounted, onUnmounted } from '../../../adapter-vue'; import { ref, onMounted, onUnmounted } from '../../../adapter-vue';
import TUIChatEngine, { import TUIChatEngine, { TUIStore, StoreName, TUIConversationService, TUITranslateService, IConversationModel } from '@tencentcloud/chat-uikit-engine';
TUIStore,
StoreName,
TUIConversationService,
TUITranslateService,
IConversationModel,
} from '@tencentcloud/chat-uikit-engine';
import { TUIGlobal, isIOS, addLongPressListener } from '@tencentcloud/universal-api'; import { TUIGlobal, isIOS, addLongPressListener } from '@tencentcloud/universal-api';
import Icon from '../../common/Icon.vue'; import Icon from '../../common/Icon.vue';
import Avatar from '../../common/Avatar/index.vue'; import Avatar from '../../common/Avatar/index.vue';
@ -134,13 +119,13 @@ const conversationList = ref<IConversationModel[]>([]);
const conversationListDomRef = ref<HTMLElement | undefined>(); const conversationListDomRef = ref<HTMLElement | undefined>();
const conversationListInnerDomRef = ref<HTMLElement | undefined>(); const conversationListInnerDomRef = ref<HTMLElement | undefined>();
const actionsMenuPosition = ref<{ const actionsMenuPosition = ref<{
top: number; top: number;
left: number | undefined; left: number | undefined;
conversationHeight: number | undefined; conversationHeight: number | undefined;
}>({ }>({
top: 0, top: 0,
left: undefined, left: undefined,
conversationHeight: undefined, conversationHeight: undefined
}); });
const displayOnlineStatus = ref(false); const displayOnlineStatus = ref(false);
const userOnlineStatusMap = ref<IUserStatusMap>(); const userOnlineStatusMap = ref<IUserStatusMap>();
@ -148,151 +133,141 @@ const userOnlineStatusMap = ref<IUserStatusMap>();
let lastestOpenActionsMenuTime: number | null = null; let lastestOpenActionsMenuTime: number | null = null;
onMounted(() => { onMounted(() => {
console.log(conversationList) TUIStore.watch(StoreName.CONV, {
TUIStore.watch(StoreName.CONV, { currentConversationID: onCurrentConversationIDUpdated,
currentConversationID: onCurrentConversationIDUpdated, conversationList: onConversationListUpdated,
conversationList: onConversationListUpdated, currentConversation: onCurrentConversationUpdated
currentConversation: onCurrentConversationUpdated, });
});
TUIStore.watch(StoreName.USER, { TUIStore.watch(StoreName.USER, {
displayOnlineStatus: onDisplayOnlineStatusUpdated, displayOnlineStatus: onDisplayOnlineStatusUpdated,
userStatusList: onUserStatusListUpdated, userStatusList: onUserStatusListUpdated
}); });
if (!isUniFrameWork && isIOS && !isPC) { if (!isUniFrameWork && isIOS && !isPC) {
addLongPressHandler(); addLongPressHandler();
} }
}); });
onUnmounted(() => { onUnmounted(() => {
TUIStore.unwatch(StoreName.CONV, { TUIStore.unwatch(StoreName.CONV, {
currentConversationID: onCurrentConversationIDUpdated, currentConversationID: onCurrentConversationIDUpdated,
conversationList: onConversationListUpdated, conversationList: onConversationListUpdated,
currentConversation: onCurrentConversationUpdated, currentConversation: onCurrentConversationUpdated
}); });
TUIStore.unwatch(StoreName.USER, { TUIStore.unwatch(StoreName.USER, {
displayOnlineStatus: onDisplayOnlineStatusUpdated, displayOnlineStatus: onDisplayOnlineStatusUpdated,
userStatusList: onUserStatusListUpdated, userStatusList: onUserStatusListUpdated
}); });
}); });
const isShowUserOnlineStatus = (conversation: IConversationModel): boolean => { const isShowUserOnlineStatus = (conversation: IConversationModel): boolean => {
return ( return displayOnlineStatus.value && conversation.type === TUIChatEngine.TYPES.CONV_C2C;
displayOnlineStatus.value
&& conversation.type === TUIChatEngine.TYPES.CONV_C2C
);
}; };
const showConversationActionMenu = ( const showConversationActionMenu = (event: Event, conversation: IConversationModel, index: number, isContextMenuEvent?: boolean) => {
event: Event, if (isContextMenuEvent) {
conversation: IConversationModel, event.preventDefault();
index: number, if (isUniFrameWork) {
isContextMenuEvent?: boolean, return;
) => { }
if (isContextMenuEvent) { }
event.preventDefault(); currentConversation.value = conversation;
if (isUniFrameWork) { lastestOpenActionsMenuTime = Date.now();
return; getActionsMenuPosition(event, index);
}
}
currentConversation.value = conversation;
lastestOpenActionsMenuTime = Date.now();
getActionsMenuPosition(event, index);
}; };
const closeConversationActionMenu = () => { const closeConversationActionMenu = () => {
// Prevent continuous triggering of overlay tap events // Prevent continuous triggering of overlay tap events
if ( if (lastestOpenActionsMenuTime && Date.now() - lastestOpenActionsMenuTime > 300) {
lastestOpenActionsMenuTime currentConversation.value = undefined;
&& Date.now() - lastestOpenActionsMenuTime > 300 isShowOverlay.value = false;
) { }
currentConversation.value = undefined;
isShowOverlay.value = false;
}
}; };
const getActionsMenuPosition = (event: Event, index: number) => { const getActionsMenuPosition = (event: Event, index: number) => {
if (isUniFrameWork) { if (isUniFrameWork) {
if (typeof conversationListDomRef.value === 'undefined') { if (typeof conversationListDomRef.value === 'undefined') {
emits('getPassingRef', conversationListDomRef); emits('getPassingRef', conversationListDomRef);
} }
const query = TUIGlobal?.createSelectorQuery().in(conversationListDomRef.value); const query = TUIGlobal?.createSelectorQuery().in(conversationListDomRef.value);
query.select(`#convlistitem-${index}`).boundingClientRect((data) => { query
if (data) { .select(`#convlistitem-${index}`)
actionsMenuPosition.value = { .boundingClientRect((data) => {
// The uni-page-head of uni-h5 is not considered a member of the viewport, so the height of the head is manually increased. if (data) {
top: data.bottom + (isH5 ? 44 : 0), actionsMenuPosition.value = {
// @ts-expect-error in uniapp event has touches property // The uni-page-head of uni-h5 is not considered a member of the viewport, so the height of the head is manually increased.
left: event.touches[0].pageX, top: data.bottom + (isH5 ? 44 : 0),
conversationHeight: data.height, // @ts-expect-error in uniapp event has touches property
}; left: event.touches[0].pageX,
isShowOverlay.value = true; conversationHeight: data.height
} };
}).exec(); isShowOverlay.value = true;
} else { }
const rect = ((event.currentTarget || event.target) as HTMLElement)?.getBoundingClientRect() || {}; })
if (rect) { .exec();
actionsMenuPosition.value = { } else {
top: rect.bottom, const rect = ((event.currentTarget || event.target) as HTMLElement)?.getBoundingClientRect() || {};
left: isPC ? (event as MouseEvent).clientX : undefined, if (rect) {
conversationHeight: rect.height, actionsMenuPosition.value = {
}; top: rect.bottom,
} left: isPC ? (event as MouseEvent).clientX : undefined,
isShowOverlay.value = true; conversationHeight: rect.height
} };
}
isShowOverlay.value = true;
}
}; };
const enterConversationChat = (conversationID: string) => { const enterConversationChat = (conversationID: string) => {
emits('handleSwitchConversation', conversationID); emits('handleSwitchConversation', conversationID);
TUIConversationService.switchConversation(conversationID); TUIConversationService.switchConversation(conversationID);
}; };
function addLongPressHandler() { function addLongPressHandler() {
if (!conversationListInnerDomRef.value) { if (!conversationListInnerDomRef.value) {
return; return;
} }
addLongPressListener({ addLongPressListener({
element: conversationListInnerDomRef.value, element: conversationListInnerDomRef.value,
onLongPress: (event, target) => { onLongPress: (event, target) => {
const index = (Array.from(conversationListInnerDomRef.value!.children) as HTMLElement[]).indexOf(target!); const index = (Array.from(conversationListInnerDomRef.value!.children) as HTMLElement[]).indexOf(target!);
showConversationActionMenu(event, conversationList.value[index], index); showConversationActionMenu(event, conversationList.value[index], index);
}, },
options: { options: {
eventDelegation: { eventDelegation: {
subSelector: '.tui-conversation-content', subSelector: '.tui-conversation-content'
}, }
}, }
}); });
} }
function onCurrentConversationUpdated(conversation: IConversationModel) { function onCurrentConversationUpdated(conversation: IConversationModel) {
currentConversation.value = conversation; currentConversation.value = conversation;
} }
function onConversationListUpdated(list: IConversationModel[]) { function onConversationListUpdated(list: IConversationModel[]) {
conversationList.value = list; conversationList.value = list;
console.log('会话列表数据', conversationList.value);
console.log('Conversation实例:', TUIStore);
} }
function onCurrentConversationIDUpdated(id: string) { function onCurrentConversationIDUpdated(id: string) {
currentConversationID.value = id; currentConversationID.value = id;
} }
function onDisplayOnlineStatusUpdated(status: boolean) { function onDisplayOnlineStatusUpdated(status: boolean) {
displayOnlineStatus.value = status; displayOnlineStatus.value = status;
} }
function onUserStatusListUpdated(list: Map<string, IUserStatus>) { function onUserStatusListUpdated(list: Map<string, IUserStatus>) {
if (list.size !== 0) { if (list.size !== 0) {
userOnlineStatusMap.value = [...list.entries()].reduce( userOnlineStatusMap.value = [...list.entries()].reduce((obj, [key, value]) => {
(obj, [key, value]) => { obj[key] = value;
obj[key] = value; return obj;
return obj; }, {} as IUserStatusMap);
}, }
{} as IUserStatusMap,
);
}
} }
// Expose to the parent component and close actionsMenu when a sliding event is detected // Expose to the parent component and close actionsMenu when a sliding event is detected
defineExpose({ closeChildren: closeConversationActionMenu }); defineExpose({ closeChildren: closeConversationActionMenu });
@ -301,11 +276,11 @@ defineExpose({ closeChildren: closeConversationActionMenu });
<style lang="scss" scoped src="./style/index.scss"></style> <style lang="scss" scoped src="./style/index.scss"></style>
<style lang="scss" scoped> <style lang="scss" scoped>
.disable-select { .disable-select {
-webkit-touch-callout:none; -webkit-touch-callout: none;
-webkit-user-select:none; -webkit-user-select: none;
-khtml-user-select:none; -khtml-user-select: none;
-moz-user-select:none; -moz-user-select: none;
-ms-user-select:none; -ms-user-select: none;
user-select:none; user-select: none;
} }
</style> </style>

35
api/checkInfo.js Normal file
View File

@ -0,0 +1,35 @@
/**
* @description 文本内容审核
* AuditName:1600080789_1745821176_amtwGf
* ContentType:Text|Image|Audio|Video
* Content:需要审核的文本内容
* ExtSender:im的id这里对应的是用户手机号
* ExtReceiver:接收方的信息选填
*/
import {
http,
Method
} from "@/utils/request.js";
export function checkText({
ExtSender,
Content,
}) {
return http.request({
url: 'https://console.tim.qq.com/v4/im_msg_audit/content_moderation'
method: Method.POST,
params: {
sdkappid: '1600080789',
identifier: 'administrator',
usersig: 'eJwtjEELgjAYhv-LroV9zi2n0CU6VBSRJV28jLbiK7SxjRxE-z1Tj*-zvDwfct6dore2JCc0AjLtNyrdeLxhj6WqsUHnrfQvOx6cekpjUJE8ngOAgFRkg9HBoNUd55zTTg3UY-1nKeOCJomIxwreu76BMnv4TcGXZTVrgMVMFm6795NQH8OateqK7CBbu7oYWJDvD4AYNPU_',
random: Math.floor(Math.random() * (4294967295 + 1)),
contenttype: 'json'
},
data: {
AuditName: '1600080789_1745821176_amtwGf'
ContentType: 'Text',
Content,
ExtSender
}
});
}

View File

@ -192,7 +192,7 @@
<!-- 4.分享 --> <!-- 4.分享 -->
<view <view
v-if="item.isShowProgressBarTime == false" v-if="item.isShowProgressBarTime == false"
@click="share" @click="share(item)"
style="opacity: 0.9; margin-top: 17px" style="opacity: 0.9; margin-top: 17px"
> >
<image <image
@ -415,6 +415,7 @@
:thisVlogId="pinglunInfo.vlogId" :thisVlogId="pinglunInfo.vlogId"
:vlogUrl="pinglunInfo.url" :vlogUrl="pinglunInfo.url"
:isPrivate="pinglunInfo.isPrivate" :isPrivate="pinglunInfo.isPrivate"
:vlogItem="pinglunInfo"
></uni-popup-share> ></uni-popup-share>
</uni-popup> </uni-popup>
</view> </view>
@ -984,6 +985,7 @@ export default {
}, 50); }, 50);
} else { } else {
this.noData = '暂无数据'; this.noData = '暂无数据';
this.isShow1 = false;
} }
} else { } else {
uni.showToast({ uni.showToast({
@ -1103,7 +1105,8 @@ export default {
animation: true animation: true
}); });
}, },
share() { share(item) {
this.pinglunInfo = item;
this.$refs.share.open(); this.$refs.share.open();
uni.hideTabBar({ uni.hideTabBar({
animation: true animation: true

View File

@ -192,7 +192,7 @@
<!-- 4.分享 --> <!-- 4.分享 -->
<view <view
v-if="item.isShowProgressBarTime == false" v-if="item.isShowProgressBarTime == false"
@click="share" @click="share(item)"
style="opacity: 0.9; margin-top: 17px" style="opacity: 0.9; margin-top: 17px"
> >
<image <image
@ -415,6 +415,7 @@
:thisVlogId="pinglunInfo.vlogId" :thisVlogId="pinglunInfo.vlogId"
:vlogUrl="pinglunInfo.url" :vlogUrl="pinglunInfo.url"
:isPrivate="pinglunInfo.isPrivate" :isPrivate="pinglunInfo.isPrivate"
:vlogItem="pinglunInfo"
></uni-popup-share> ></uni-popup-share>
</uni-popup> </uni-popup>
</view> </view>
@ -985,6 +986,7 @@ export default {
}, 50); }, 50);
} else { } else {
this.noData = '暂无数据'; this.noData = '暂无数据';
this.isShow1 = false;
return; return;
} }
} else { } else {
@ -1105,7 +1107,8 @@ export default {
animation: true animation: true
}); });
}, },
share() { share(item) {
this.pinglunInfo = item;
this.$refs.share.open(); this.$refs.share.open();
uni.hideTabBar({ uni.hideTabBar({
animation: true animation: true

View File

@ -185,7 +185,7 @@
<!-- 4.分享 --> <!-- 4.分享 -->
<view <view
v-if="item.isShowProgressBarTime == false" v-if="item.isShowProgressBarTime == false"
@click="share" @click="share(item)"
style="opacity: 0.9; margin-top: 17px" style="opacity: 0.9; margin-top: 17px"
> >
<image <image
@ -408,6 +408,7 @@
:thisVlogId="pinglunInfo.vlogId" :thisVlogId="pinglunInfo.vlogId"
:vlogUrl="pinglunInfo.url" :vlogUrl="pinglunInfo.url"
:isPrivate="pinglunInfo.isPrivate" :isPrivate="pinglunInfo.isPrivate"
:vlogItem="pinglunInfo"
></uni-popup-share> ></uni-popup-share>
</uni-popup> </uni-popup>
</view> </view>
@ -1087,7 +1088,8 @@ export default {
animation: true animation: true
}); });
}, },
share() { share(item) {
this.pinglunInfo = item;
this.$refs.share.open(); this.$refs.share.open();
uni.hideTabBar({ uni.hideTabBar({
animation: true animation: true

View File

@ -17,7 +17,7 @@ const prod = {
// buyer: "https://buyer-api.pickmall.cn", // buyer: "https://buyer-api.pickmall.cn",
common: "http://192.168.1.211:8890", common: "http://192.168.1.211:8890",
buyer: "http://192.168.1.211:8888", buyer: "http://192.168.1.211:8888",
vlog: "http://192.168.1.86:8099", vlog: "http://192.168.1.211:8099",
}; };
//默认生产环境 //默认生产环境

View File

@ -270,7 +270,7 @@ export default {
onShow() { onShow() {
let me = this; let me = this;
// 判断我有没有登录 // 判断我有没有登录
this.userIsLogin = filters.isLogin('auth'); this.userIsLogin = storage.getHasLogin();
console.log(this.userIsLogin); console.log(this.userIsLogin);
if (this.userIsLogin) { if (this.userIsLogin) {
this.getUinfo(); this.getUinfo();
@ -280,9 +280,9 @@ export default {
}, },
onTabItemTap: (e) => { onTabItemTap: (e) => {
console.log(e); console.log(e);
if (!filters.isLogin('auth')) { if (!storage.getHasLogin()) {
uni.navigateTo({ uni.navigateTo({
url: '/pages/passport/login?init=index' url: '/pages/passport/login'
}); });
} }
}, },

View File

@ -195,7 +195,7 @@
<!-- 4.分享 --> <!-- 4.分享 -->
<view <view
v-if="item.isShowProgressBarTime == false" v-if="item.isShowProgressBarTime == false"
@click="share" @click="share(item)"
style="opacity: 0.9; margin-top: 17px" style="opacity: 0.9; margin-top: 17px"
> >
<image <image
@ -418,6 +418,7 @@
:thisVlogId="pinglunInfo.vlogId" :thisVlogId="pinglunInfo.vlogId"
:vlogUrl="pinglunInfo.url" :vlogUrl="pinglunInfo.url"
:isPrivate="pinglunInfo.isPrivate" :isPrivate="pinglunInfo.isPrivate"
:vlogItem="pinglunInfo"
></uni-popup-share> ></uni-popup-share>
</uni-popup> </uni-popup>
</view> </view>
@ -1123,7 +1124,8 @@ export default {
animation: true animation: true
}); });
}, },
share() { share(item) {
this.pinglunInfo = item;
this.$refs.share.open(); this.$refs.share.open();
uni.hideTabBar({ uni.hideTabBar({
animation: true animation: true

View File

@ -1,329 +1,372 @@
<template> <template>
<view class="person-msg"> <view class="person-msg">
<view class="head c-content" @click="changeFace"> <view
<image :src="form.face || '/static/missing-face.png'" mode=""></image> class="head c-content"
<view>点击修改头像</view> @click="changeFace"
</view> >
<u-form :model="form" ref="uForm" class="form"> <image
<u-form-item label="昵称" label-width="150"> :src="form.face || '/static/missing-face.png'"
<u-input mode=""
v-model="form.nickName" ></image>
placeholder="请输入昵称" <view>点击修改头像</view>
maxlength="10" </view>
/> <u-form
</u-form-item> :model="form"
<u-form-item label="二维码" label-width="150"> ref="uForm"
<img :src="erwei" alt="" width="60" @click="showQrCodeInFullSize" /> class="form"
</u-form-item> >
<u-form-item label="性别" label-width="150"> <u-form-item
<u-radio-group v-model="form.sex" :active-color="lightColor"> label="昵称"
<u-radio name="1"></u-radio> label-width="150"
<u-radio name="0"></u-radio> >
</u-radio-group> <u-input
</u-form-item> v-model="form.nickName"
<u-form-item label="生日" label-width="150" right-icon="arrow-right"> placeholder="请输入昵称"
<div style="width: 100%" @click="showBirthday = true"> maxlength="10"
{{ birthday || "请选择出生日期" }} />
</div> </u-form-item>
<u-picker <u-form-item
v-model="showBirthday" label="二维码"
mode="time" label-width="150"
:confirm-color="lightColor" >
@confirm="selectTime" <img
></u-picker> :src="erwei"
</u-form-item> alt=""
width="60"
@click="showQrCodeInFullSize"
/>
</u-form-item>
<u-form-item
label="性别"
label-width="150"
>
<u-radio-group
v-model="form.sex"
:active-color="lightColor"
>
<u-radio name="1"></u-radio>
<u-radio name="0"></u-radio>
</u-radio-group>
</u-form-item>
<u-form-item
label="生日"
label-width="150"
right-icon="arrow-right"
>
<div
style="width: 100%"
@click="showBirthday = true"
>
{{ birthday || '请选择出生日期' }}
</div>
<u-picker
v-model="showBirthday"
mode="time"
:confirm-color="lightColor"
@confirm="selectTime"
></u-picker>
</u-form-item>
<u-form-item <u-form-item
label="城市" label="城市"
label-width="150" label-width="150"
placeholder="请选择城市" placeholder="请选择城市"
right-icon="arrow-right" right-icon="arrow-right"
> >
<div <div
style=" style="width: 32vh; white-space: nowrap; overflow: hidden; text-overflow: ellipsis"
width: 32vh; @click="clickRegion"
white-space: nowrap; >
overflow: hidden; {{ form.___path || '请选择城市' }}
text-overflow: ellipsis; </div>
" </u-form-item>
@click="clickRegion" </u-form>
> <div style="display: flex; justify-content: center"></div>
{{ form.___path || "请选择城市" }} <div class="bottom">
</div> <view
</u-form-item> class="submit"
</u-form> @click="submit"
<div style="display: flex; justify-content: center"></div> >
<div class="bottom"> 保存
<view class="submit" @click="submit">保存</view> </view>
<view class="submit light" @click="showModalDialog">退出登录</view> <view
</div> class="submit light"
<u-modal @click="showModalDialog"
show-cancel-button >
v-model="quitShow" 退出登录
@confirm="confirm" </view>
:confirm-color="lightColor" </div>
:async-close="true" <u-modal
:content="userInfo.id ? '确定要退出登录么?' : '确定要返回登录么?'" show-cancel-button
></u-modal> v-model="quitShow"
<m-city @confirm="confirm"
:provinceData="region" :confirm-color="lightColor"
headTitle="区域选择" :async-close="true"
ref="cityPicker" :content="userInfo.id ? '确定要退出登录么?' : '确定要返回登录么?'"
@funcValue="getpickerParentValue" ></u-modal>
pickerSize="4" <m-city
></m-city> :provinceData="region"
</view> headTitle="区域选择"
ref="cityPicker"
@funcValue="getpickerParentValue"
pickerSize="4"
></m-city>
</view>
</template> </template>
<script> <script>
import { saveUserInfo, geterwei } from "@/api/members.js"; import { saveUserInfo, geterwei } from '@/api/members.js';
import { upload } from "@/api/common.js"; import { upload } from '@/api/common.js';
import { logout } from "@/api/login"; import { logout } from '@/api/login';
import storage from "@/utils/storage.js"; import storage from '@/utils/storage.js';
import uFormItem from "@/uview-ui/components/u-form-item/u-form-item.vue"; import uFormItem from '@/uview-ui/components/u-form-item/u-form-item.vue';
import gkcity from "@/components/m-city/m-city.vue"; import gkcity from '@/components/m-city/m-city.vue';
import { clearIm } from '@/utils/handleim.js';
export default { export default {
components: { components: {
uFormItem, uFormItem,
"m-city": gkcity, 'm-city': gkcity
}, },
data() { data() {
return { return {
erwei: "", erwei: '',
quitShow: false, quitShow: false,
userInfo: {}, userInfo: {},
lightColor: this.$lightColor, // lightColor: this.$lightColor, //
form: { form: {
nickName: storage.getUserInfo().nickName || "", nickName: storage.getUserInfo().nickName || '',
birthday: storage.getUserInfo().birthday || "", birthday: storage.getUserInfo().birthday || '',
face: storage.getUserInfo().face || "/static/imlogo.png", // face: storage.getUserInfo().face || '/static/imlogo.png', //
regionId: [], //Id regionId: [], //Id
region: storage.getUserInfo().region || [], // region: storage.getUserInfo().region || [], //
sex: storage.getUserInfo().sex, // sex: storage.getUserInfo().sex, //
___path: storage.getUserInfo().region, ___path: storage.getUserInfo().region
}, },
birthday: storage.getUserInfo().birthday || "", // birthday: storage.getUserInfo().birthday || '', //
photo: [ photo: [
{ {
text: "立即拍照", text: '立即拍照',
color: this.$mainColor, color: this.$mainColor
}, },
{ {
text: "从相册选择", text: '从相册选择',
color: this.$mainColor, color: this.$mainColor
}, }
], ],
region: [ region: [
// //
{ {
id: "", id: '',
localName: "请选择", localName: '请选择',
children: [], children: []
}, }
], ],
showBirthday: false, // showBirthday: false //
}; };
}, },
onShow() { onShow() {
this.userInfo = this.$options.filters.isLogin(); this.userInfo = this.$options.filters.isLogin();
this.getgeterwei(); this.getgeterwei();
}, },
methods: { methods: {
showQrCodeInFullSize() { showQrCodeInFullSize() {
uni.previewImage({ uni.previewImage({
urls: [this.erwei], urls: [this.erwei],
current: this.erwei, current: this.erwei
}); });
}, },
getgeterwei() { getgeterwei() {
geterwei().then((res) => { geterwei().then((res) => {
this.erwei = res.data.result; this.erwei = res.data.result;
}); });
}, },
showModalDialog() { showModalDialog() {
this.quitShow = true; this.quitShow = true;
}, },
clear() { clear() {
storage.setAccessToken(""); storage.setRefreshVlogIndex('1'); //
storage.setRefreshToken(""); storage.setHasLogin(false);
storage.setUserInfo({}); storage.setAccessToken('');
// vlog storage.setRefreshToken('');
storage.setVlogToken(""); storage.setUuid('');
storage.setVlogUserInfo({}); storage.setUserInfo({});
this.$options.filters.navigateToLogin("redirectTo"); // vlog
}, storage.setVlogToken('');
/** storage.setVlogUserInfo(null);
* 确认退出 //
* 清除缓存重新登录 storage.setRefreshVlogIndex('1'); //
*/ // 退im
async confirm() { clearIm();
await logout(); this.$options.filters.navigateToLogin('redirectTo');
this.clear(); },
}, /**
/** * 确认退出
* 退出登录 * 清除缓存重新登录
*/ */
quiteLoginOut() { async confirm() {
this.$options.filters.quiteLoginOut(); await logout();
}, this.clear();
/** },
* 选择地址回调 /**
*/ * 退出登录
getpickerParentValue(e) { */
this.form.region = []; quiteLoginOut() {
this.form.regionId = []; this.$options.filters.quiteLoginOut();
let name = ""; },
/**
* 选择地址回调
*/
getpickerParentValue(e) {
this.form.region = [];
this.form.regionId = [];
let name = '';
e.forEach((item, index) => { e.forEach((item, index) => {
if (item.id) { if (item.id) {
this.form.region.push(item.localName); this.form.region.push(item.localName);
this.form.regionId.push(item.id); this.form.regionId.push(item.id);
if (index == e.length - 1) { if (index == e.length - 1) {
name += item.localName; name += item.localName;
} else { } else {
name += item.localName + ","; name += item.localName + ',';
} }
this.form.___path = name; this.form.___path = name;
} }
}); });
}, },
/** /**
* 点击选择地址 * 点击选择地址
*/ */
clickRegion() { clickRegion() {
this.$refs.cityPicker.show(); this.$refs.cityPicker.show();
}, },
/** /**
* 提交保存 * 提交保存
*/ */
submit() { submit() {
delete this.form.___path; delete this.form.___path;
let params = JSON.parse(JSON.stringify(this.form)); let params = JSON.parse(JSON.stringify(this.form));
saveUserInfo(params).then((res) => { saveUserInfo(params).then((res) => {
if (res.statusCode == 200) { if (res.statusCode == 200) {
storage.setUserInfo(res.data.result); storage.setUserInfo(res.data.result);
uni.navigateBack(); uni.navigateBack();
} }
}); });
}, },
/** /**
* 修改头像 * 修改头像
*/ */
changeFace(index) { changeFace(index) {
uni.chooseImage({ uni.chooseImage({
success: (chooseImageRes) => { success: (chooseImageRes) => {
const tempFilePaths = chooseImageRes.tempFilePaths; const tempFilePaths = chooseImageRes.tempFilePaths;
uni.uploadFile({ uni.uploadFile({
url: upload, url: upload,
filePath: tempFilePaths[0], filePath: tempFilePaths[0],
name: "file", name: 'file',
header: { header: {
accessToken: storage.getAccessToken(), accessToken: storage.getAccessToken()
}, },
success: (uploadFileRes) => { success: (uploadFileRes) => {
let data = JSON.parse(uploadFileRes.data); let data = JSON.parse(uploadFileRes.data);
this.form.face = data.result; this.form.face = data.result;
}, }
}); });
}, }
}); });
}, },
/** /**
* 选择地址 * 选择地址
*/ */
selectRegion(region) { selectRegion(region) {
this.$set( this.$set(this.form, 'address', `${region.province.label} ${region.city.label} ${region.area.label}`);
this.form, },
"address",
`${region.province.label} ${region.city.label} ${region.area.label}`
);
},
/** /**
* 选择时间 * 选择时间
*/ */
selectTime(time) { selectTime(time) {
this.form.birthday = `${time.year}-${time.month}-${time.day}`; this.form.birthday = `${time.year}-${time.month}-${time.day}`;
this.birthday = `${time.year} - ${time.month} - ${time.day}`; this.birthday = `${time.year} - ${time.month} - ${time.day}`;
}, }
}, },
/** /**
* 加载数据 * 加载数据
*/ */
onLoad() {}, onLoad() {}
}; };
</script> </script>
<style lang="scss" scoped> <style lang="scss" scoped>
.submit { .submit {
height: 90rpx; height: 90rpx;
line-height: 90rpx; line-height: 90rpx;
text-align: center; text-align: center;
margin-top: 90rpx; margin-top: 90rpx;
width: 100%; width: 100%;
margin: 0 auto; margin: 0 auto;
color: $main-color; color: $main-color;
border-radius: 100px; border-radius: 100px;
} }
.head { .head {
height: 260rpx; height: 260rpx;
color: $font-color-light; color: $font-color-light;
font-size: $font-sm; font-size: $font-sm;
display: flex; display: flex;
flex-direction: column; flex-direction: column;
justify-content: center; justify-content: center;
align-items: center; align-items: center;
line-height: 2em; line-height: 2em;
image { image {
width: 144rpx; width: 144rpx;
height: 144rpx; height: 144rpx;
border-radius: 50%; border-radius: 50%;
} }
} }
/deep/ .u-form { /deep/ .u-form {
background-color: #ffffff; background-color: #ffffff;
padding: 0; padding: 0;
margin-top: 30rpx; margin-top: 30rpx;
.u-form-item { .u-form-item {
padding: 0 20rpx; padding: 0 20rpx;
height: 110rpx; height: 110rpx;
line-height: 110rpx; line-height: 110rpx;
} }
} }
.form { .form {
background-color: #ffffff; background-color: #ffffff;
} }
.bottom { .bottom {
position: fixed; position: fixed;
bottom: 40px; bottom: 40px;
display: flex; display: flex;
align-items: center; align-items: center;
width: 100%; width: 100%;
> .submit { > .submit {
background: $light-color; background: $light-color;
background: #fe3c3c; background: #fe3c3c;
color: #fff; color: #fff;
width: 40%; width: 40%;
} }
} }
::v-deep { ::v-deep {
.u-radio__icon-wrap--checked { .u-radio__icon-wrap--checked {
// background: #FE3C3C; // background: #FE3C3C;
// border: 1px solid #FE3C3C; // border: 1px solid #FE3C3C;
border-color: #fe3c3c !important; border-color: #fe3c3c !important;
background-color: #fe3c3c !important; background-color: #fe3c3c !important;
} }
} }
.u-form-item div { .u-form-item div {

View File

@ -1,231 +1,273 @@
<template> <template>
<view class="container"> <view class="container">
<view class="person" @click="checkUserInfo()"> <view
<u-image width=140 height="140" shape="circle" :src="userInfo.face || '/static/missing-face.png'" mode=""> class="person"
</u-image> @click="checkUserInfo()"
<view class="user-name"> >
<u-image
{{ userInfo.id ? userInfo.nickName || '' : '暂未登录' }} width="140"
</view> height="140"
<u-icon color="#ccc" name="arrow-right"></u-icon> shape="circle"
</view> :src="userInfo.face || '/static/missing-face.png'"
<!-- #ifdef MP-WEIXIN --> mode=""
<view style="height: 20rpx; width: 100%"></view> ></u-image>
<!-- #endif --> <view class="user-name">
<u-cell-group :border="false"> {{ userInfo.id ? userInfo.nickName || '' : '暂未登录' }}
<!-- #ifdef APP-PLUS --> </view>
<u-cell-item title="清除缓存" :value="fileSizeString" @click="clearCache"></u-cell-item> <u-icon
<!-- #endif --> color="#ccc"
<u-cell-item title="安全中心" @click="navigateTo('/pages/mine/set/securityCenter/securityCenter')"></u-cell-item> name="arrow-right"
<u-cell-item title="意见反馈" @click="navigateTo('/pages/mine/set/feedBack')"></u-cell-item> ></u-icon>
<!-- #ifndef H5 --> </view>
<!-- #endif --> <!-- #ifdef MP-WEIXIN -->
<u-cell-item :title="`关于我们`" @click="navigateTo('/pages/mine/set/editionIntro')"></u-cell-item> <view style="height: 20rpx; width: 100%"></view>
</u-cell-group> <!-- #endif -->
<view class="submit" @click="showModalDialog">{{userInfo.id ?'退出登录':'返回登录'}}</view> <u-cell-group :border="false">
<u-modal show-cancel-button v-model="quitShow" @confirm="confirm" :confirm-color="lightColor" :async-close="true" <!-- #ifdef APP-PLUS -->
:content="userInfo.id ? '确定要退出登录么?' : '确定要返回登录么?'"></u-modal> <u-cell-item
</view> title="清除缓存"
:value="fileSizeString"
@click="clearCache"
></u-cell-item>
<!-- #endif -->
<u-cell-item
title="安全中心"
@click="navigateTo('/pages/mine/set/securityCenter/securityCenter')"
></u-cell-item>
<u-cell-item
title="意见反馈"
@click="navigateTo('/pages/mine/set/feedBack')"
></u-cell-item>
<!-- #ifndef H5 -->
<!-- #endif -->
<u-cell-item
:title="`关于我们`"
@click="navigateTo('/pages/mine/set/editionIntro')"
></u-cell-item>
</u-cell-group>
<view
class="submit"
@click="showModalDialog"
>
{{ userInfo.id ? '退出登录' : '返回登录' }}
</view>
<u-modal
show-cancel-button
v-model="quitShow"
@confirm="confirm"
:confirm-color="lightColor"
:async-close="true"
:content="userInfo.id ? '确定要退出登录么?' : '确定要返回登录么?'"
></u-modal>
</view>
</template> </template>
<script> <script>
import { logout } from "@/api/login"; import { logout } from '@/api/login';
import storage from "@/utils/storage.js"; import storage from '@/utils/storage.js';
import config from "@/config/config"; import config from '@/config/config';
import { clearIm } from '@/utils/handleim.js';
export default { export default {
data() { data() {
return { return {
config, config,
lightColor: this.$lightColor, lightColor: this.$lightColor,
quitShow: false, quitShow: false,
isCertificate: false, isCertificate: false,
userInfo: {}, userInfo: {},
fileSizeString: "0B", fileSizeString: '0B'
}; };
}, },
methods: { methods: {
navigateTo(url) { navigateTo(url) {
if (url == "/pages/set/securityCenter/securityCenter") { if (url == '/pages/set/securityCenter/securityCenter') {
url += `?mobile=${this.userInfo.mobile}`; url += `?mobile=${this.userInfo.mobile}`;
} }
uni.navigateTo({ uni.navigateTo({
url: url, url: url
}); });
}, },
clear() { clear() {
storage.setAccessToken(""); storage.setRefreshVlogIndex('1'); //
storage.setRefreshToken(""); storage.setHasLogin(false);
storage.setUserInfo({}); storage.setAccessToken('');
// vlog storage.setRefreshToken('');
storage.setVlogToken("") storage.setUuid('');
storage.setVlogUserInfo({}) storage.setUserInfo({});
this.$options.filters.navigateToLogin("redirectTo"); // vlog
}, storage.setVlogToken('');
storage.setVlogUserInfo(null);
//
storage.setRefreshVlogIndex('1'); //
// 退im
clearIm();
this.$options.filters.navigateToLogin('redirectTo');
},
/** /**
* 确认退出 * 确认退出
* 清除缓存重新登录 * 清除缓存重新登录
*/ */
async confirm() { async confirm() {
await logout(); await logout();
this.clear(); this.clear();
}, },
/** /**
* 显示退出登录对话框 * 显示退出登录对话框
*/ */
showModalDialog() { showModalDialog() {
this.quitShow = true; this.quitShow = true;
}, },
/** /**
* 读取当前缓存 * 读取当前缓存
*/ */
getCacheSize() { getCacheSize() {
// //
let that = this; let that = this;
plus.cache.calculate(function (size) { plus.cache.calculate(function (size) {
let sizeCache = parseInt(size); let sizeCache = parseInt(size);
if (sizeCache == 0) { if (sizeCache == 0) {
that.fileSizeString = "0B"; that.fileSizeString = '0B';
} else if (sizeCache < 1024) { } else if (sizeCache < 1024) {
that.fileSizeString = sizeCache + "B"; that.fileSizeString = sizeCache + 'B';
} else if (sizeCache < 1048576) { } else if (sizeCache < 1048576) {
that.fileSizeString = (sizeCache / 1024).toFixed(2) + "KB"; that.fileSizeString = (sizeCache / 1024).toFixed(2) + 'KB';
} else if (sizeCache < 1073741824) { } else if (sizeCache < 1073741824) {
that.fileSizeString = (sizeCache / 1048576).toFixed(2) + "MB"; that.fileSizeString = (sizeCache / 1048576).toFixed(2) + 'MB';
} else { } else {
that.fileSizeString = (sizeCache / 1073741824).toFixed(2) + "GB"; that.fileSizeString = (sizeCache / 1073741824).toFixed(2) + 'GB';
} }
}); });
}, },
/** /**
* 点击用户详情 * 点击用户详情
* 判断当前是否进入用户中心 * 判断当前是否进入用户中心
*/ */
checkUserInfo() { checkUserInfo() {
if (this.$options.filters.isLogin("auth")) { if (this.$options.filters.isLogin('auth')) {
this.navigateTo("/pages/mine/set/personMsg"); this.navigateTo('/pages/mine/set/personMsg');
} else { } else {
uni.showToast({ uni.showToast({
title: "当前暂无用户请登录后重试", title: '当前暂无用户请登录后重试',
duration: 2000, duration: 2000,
icon: "none", icon: 'none'
}); });
} }
}, },
/** /**
* 清除当前设备缓存 * 清除当前设备缓存
*/ */
clearCache() { clearCache() {
// //
let that = this; let that = this;
let os = plus.os.name; let os = plus.os.name;
if (os == "Android") { if (os == 'Android') {
let main = plus.android.runtimeMainActivity(); let main = plus.android.runtimeMainActivity();
let sdRoot = main.getCacheDir(); let sdRoot = main.getCacheDir();
let files = plus.android.invoke(sdRoot, "listFiles"); let files = plus.android.invoke(sdRoot, 'listFiles');
let len = files.length; let len = files.length;
for (let i = 0; i < len; i++) { for (let i = 0; i < len; i++) {
let filePath = "" + files[i]; // let filePath = '' + files[i]; //
plus.io.resolveLocalFileSystemURL( plus.io.resolveLocalFileSystemURL(
filePath, filePath,
function (entry) { function (entry) {
if (entry.isDirectory) { if (entry.isDirectory) {
entry.removeRecursively( entry.removeRecursively(
function (entry) { function (entry) {
// //
uni.showToast({ uni.showToast({
title: "缓存清理完成", title: '缓存清理完成',
duration: 2000, duration: 2000,
icon: "none", icon: 'none'
}); });
that.getCacheSize(); // that.getCacheSize(); //
}, },
function (e) {} function (e) {}
); );
} else { } else {
entry.remove(); entry.remove();
} }
}, },
function (e) { function (e) {
uni.showToast({ uni.showToast({
title: "文件路径读取失败", title: '文件路径读取失败',
duration: 2000, duration: 2000,
icon: "none", icon: 'none'
}); });
} }
); );
} }
} else { } else {
// ios // ios
plus.cache.clear(function () { plus.cache.clear(function () {
uni.showToast({ uni.showToast({
title: "缓存清理完成", title: '缓存清理完成',
duration: 2000, duration: 2000,
icon: "none", icon: 'none'
}); });
that.getCacheSize(); that.getCacheSize();
}); });
} }
}, }
}, },
onShow() { onShow() {
this.userInfo = this.$options.filters.isLogin(); this.userInfo = this.$options.filters.isLogin();
// #ifdef APP-PLUS // #ifdef APP-PLUS
this.getCacheSize(); this.getCacheSize();
// #endif // #endif
}, }
}; };
</script> </script>
<style lang='scss' scoped> <style lang="scss" scoped>
.submit { .submit {
height: 90rpx; height: 90rpx;
line-height: 90rpx; line-height: 90rpx;
text-align: center; text-align: center;
margin-top: 90rpx; margin-top: 90rpx;
background: #fff; background: #fff;
width: 100%; width: 100%;
margin: 0 auto; margin: 0 auto;
color: $main-color; color: $main-color;
} }
.person { .person {
height: 208rpx; height: 208rpx;
display: flex; display: flex;
padding: 0 20rpx; padding: 0 20rpx;
font-size: $font-base; font-size: $font-base;
justify-content: space-between; justify-content: space-between;
align-items: center; align-items: center;
margin-bottom: 20rpx; margin-bottom: 20rpx;
.user-name { .user-name {
width: 500rpx; width: 500rpx;
overflow: hidden; overflow: hidden;
text-overflow: ellipsis; text-overflow: ellipsis;
white-space: nowrap; white-space: nowrap;
margin-left: 30rpx; margin-left: 30rpx;
line-height: 2em; line-height: 2em;
font-size: 34rpx; font-size: 34rpx;
} }
} }
.u-cell { .u-cell {
height: 110rpx; height: 110rpx;
/* line-height: 110rpx; */ /* line-height: 110rpx; */
padding: 0 20rpx; padding: 0 20rpx;
align-items: center; align-items: center;
color: #333333; color: #333333;
} }
/deep/ .u-cell__value { /deep/ .u-cell__value {
color: #cccccc !important; color: #cccccc !important;
} }
/deep/ .u-cell__right-icon-wrap { /deep/ .u-cell__right-icon-wrap {
color: #cccccc !important; color: #cccccc !important;
} }
</style> </style>

File diff suppressed because it is too large Load Diff

View File

@ -95,6 +95,7 @@ import api from '@/config/api.js';
export default { export default {
data() { data() {
return { return {
upFlage: true,
publishTouched: false, publishTouched: false,
preplayTouched: false, preplayTouched: false,
tempFilePath: '', tempFilePath: '',
@ -107,6 +108,7 @@ export default {
}; };
}, },
onLoad(params) { onLoad(params) {
this.upFlage = false;
let me = this; let me = this;
let vlogInfo = storage.getVlogUserInfo(); let vlogInfo = storage.getVlogUserInfo();
// 上个页面传过来的文件事件对象, 其中包含了相册中选择的视频内容 // 上个页面传过来的文件事件对象, 其中包含了相册中选择的视频内容
@ -147,6 +149,9 @@ export default {
// (res.progress * 100) / res.total // (res.progress * 100) / res.total
// ); // );
me.percentCompleted = res.progress; me.percentCompleted = res.progress;
if (res.progress == 100) {
me.upFlage = true;
}
}); });
}, },
methods: { methods: {
@ -155,6 +160,9 @@ export default {
this.title = e.detail.value; this.title = e.detail.value;
}, },
doPublich() { doPublich() {
if (!this.upFlage) {
return;
}
if (this.title.length < 5) { if (this.title.length < 5) {
uni.showToast({ uni.showToast({
title: '请输入5个字以上的标题', title: '请输入5个字以上的标题',
@ -162,6 +170,10 @@ export default {
}); });
return; return;
} }
this.upFlage = false;
uni.showLoading({
title: '请稍等'
});
let me = this; let me = this;
let vlogInfo = storage.getVlogUserInfo(); let vlogInfo = storage.getVlogUserInfo();
let userId = vlogInfo.id; let userId = vlogInfo.id;
@ -187,17 +199,15 @@ export default {
data: vlog, data: vlog,
success(result) { success(result) {
if (result.data.status == 200) { if (result.data.status == 200) {
uni.showToast({ // uni.showToast({
title: result.data.msg, // title: result.data.msg,
icon: 'none', // icon: 'none',
duration: 2000 // duration: 2000
}); // });
setTimeout(() => { uni.switchTab({
uni.switchTab({ url: '/pages/me/me'
url: '/pages/me/me' });
});
}, 2000);
} else { } else {
uni.showToast({ uni.showToast({
title: result.data.msg, title: result.data.msg,
@ -205,6 +215,10 @@ export default {
duration: 3000 duration: 3000
}); });
} }
},
complete() {
this.upFlage = true;
uni.hideLoading();
} }
}); });
}, },

View File

@ -114,6 +114,10 @@ export default {
} }
data.forEach((i) => { data.forEach((i) => {
i.doIflow = false; i.doIflow = false;
if (i.followStatus == null) {
//
i.followStatus = '未关注';
}
this.flowList.push(i); this.flowList.push(i);
}); });
// this.flowList.push(...data); // this.flowList.push(...data);

File diff suppressed because it is too large Load Diff

View File

@ -210,13 +210,32 @@ export default {
let tabIndex = e.index; let tabIndex = e.index;
if (tabIndex == 0) { if (tabIndex == 0) {
var prop = this.pageList[this.curIndex]; var prop = this.pageList[this.curIndex];
this.$refs[prop].showVd(); // this.$refs[prop].showVd();
console.log('是否刷新:' + storage.getRefreshVlogIndex());
if (storage.getRefreshVlogIndex() === '1') {
try {
storage.setRefreshVlogIndex('0'); //初始完数据修改状态不需要刷新
console.log('是否刷新:' + storage.getRefreshVlogIndex());
// 登录后需要刷新数据
for (var i = 0; i < this.pageList.length; i++) {
this.$refs[i].dataList = []; //所有数据清空
}
this.$refs[prop].get(); //只初始化当前所在位置的数据
} catch (err) {
console.log(err + '255');
}
} else {
try {
this.$refs[prop].showVd();
} catch (err) {
console.log(err);
}
}
} }
}, },
onShow() { onShow() {
var prop = this.pageList[this.curIndex]; var prop = this.pageList[this.curIndex];
this.getLocation(); this.getLocation();
this.myUserInfo = storage.getVlogUserInfo();
if (storage.getRefreshVlogIndex() == '1') { if (storage.getRefreshVlogIndex() == '1') {
// 登录后需要刷新数据 // 登录后需要刷新数据
for (var i = 0; i < this.pageList.length; i++) { for (var i = 0; i < this.pageList.length; i++) {

View File

@ -5,27 +5,27 @@ import storage from "@/utils/storage";
Vue.use(Vuex); Vue.use(Vuex);
const store = new Vuex.Store({ const store = new Vuex.Store({
state: { state: {
verificationKey: "", //获取key表示验证通过 verificationKey: "", //获取key表示验证通过
distributionId:"", //分销员Id 如果当前账户从未登录过时记录 distributionId: "", //分销员Id 如果当前账户从未登录过时记录
hasLogin: storage.getHasLogin(), hasLogin: storage.getHasLogin(),
userInfo: storage.getUserInfo(), userInfo: storage.getUserInfo(),
uuid: storage.getUuid(), uuid: storage.getUuid(),
token: "", token: "",
}, },
mutations: { mutations: {
login(state, userInfo) { login(state, userInfo) {
state.userInfo = userInfo || {}; state.userInfo = userInfo || {};
state.userName = state.userName =
userInfo.Name || userInfo.Nickname || userInfo.Username || "匿名用户"; userInfo.Name || userInfo.Nickname || userInfo.Username || "匿名用户";
state.hasLogin = true; state.hasLogin = true;
}, },
logout(state) { logout(state) {
state.userName = ""; state.userName = "";
state.hasLogin = false; state.hasLogin = false;
}, },
}, },
actions: {}, actions: {},
}); });
export default store; export default store;

View File

@ -15,13 +15,16 @@
.all-box { .all-box {
display: flex; display: flex;
flex-direction: row; flex-direction: row;
justify-content: space-around; /* justify-content: space-around; */
height: 280rpx; height: 280rpx;
} }
.share-item { .share-item {
display: flex; display: flex;
flex-direction: column; flex-direction: column;
margin-top: 60rpx; margin-top: 60rpx;
margin-left: 20rpx;
margin-right: 20rpx;
width: 120rpx;
} }
.icon-wrapper { .icon-wrapper {
width: 120rpx; width: 120rpx;
@ -39,8 +42,12 @@
} }
.icon-tag-text { .icon-tag-text {
color: #ffffff; color: #ffffff;
width: 120rpx;
font-size: 14px; font-size: 14px;
margin-top: 10rpx; margin-top: 10rpx;
lines: 1;
text-overflow: ellipsis;
text-align: center;
} }
</style> </style>
@ -70,6 +77,7 @@
</view> --> </view> -->
<view <view
v-if="userId == ''"
class="share-item" class="share-item"
@click="copyLink()" @click="copyLink()"
> >
@ -90,6 +98,73 @@
复制链接 复制链接
</text> </text>
</view> </view>
<!-- 会话列表 storage.getHasLogin() -->
<scroll-view
v-if="userId != ''"
:scroll-x="true"
:show-scrollbar="false"
class="all-box"
>
<view
class="share-item"
@click="copyLink()"
>
<view
class="icon-wrapper"
style="align-self: center"
>
<image
class="icon-image"
src="/static/images/link.png"
style="align-self: center"
></image>
</view>
<text
class="icon-tag-text"
style="align-self: center"
>
复制链接
</text>
</view>
<view
v-for="(i, index) in converList"
:key="index"
class="share-item"
@click="toIm(i)"
>
<view
class="icon-wrapper"
style="align-self: center"
>
<image
v-if="i.type == 'C2C'"
class="icon-image"
:src="i.userProfile.avatar || ''"
style="align-self: center"
></image>
<image
v-if="i.type == 'GROUP'"
class="icon-image"
:src="i.groupProfile.avatar || ''"
style="align-self: center"
></image>
</view>
<text
v-if="i.type == 'C2C'"
class="icon-tag-text"
style="align-self: center"
>
{{ i.userProfile.nick || '' }}
</text>
<text
v-if="i.type == 'GROUP'"
class="icon-tag-text"
style="align-self: center"
>
{{ i.groupProfile.name || '' }}
</text>
</view>
</scroll-view>
<!-- <view <!-- <view
class="share-item" class="share-item"
@ -190,8 +265,10 @@
<script> <script>
import storage from '@/utils/storage.js'; // import storage from '@/utils/storage.js'; //
import config from '@/config/config.js';
import { vlogChangeToPublic, vlogChangeToPrivate } from '@/api/vlog'; import { vlogChangeToPublic, vlogChangeToPrivate } from '@/api/vlog';
import { dateFormat, graceNumber, getDateBeforeNow } from '@/utils/tools.js'; import { dateFormat, graceNumber, getDateBeforeNow } from '@/utils/tools.js';
import { conversationData, sendVlogCustomMsg } from '@/utils/handleim.js';
import popup from '../uni-popup/popup.js'; import popup from '../uni-popup/popup.js';
export default { export default {
name: 'UniPopupShare', name: 'UniPopupShare',
@ -221,12 +298,15 @@ export default {
isPrivate: { isPrivate: {
type: Number, type: Number,
default: 0 default: 0
} },
vlogItem: {}
}, },
data() { data() {
return { return {
userId: '', userId: '',
cancelTouched: false cancelTouched: false,
converList: [],
flag: true
}; };
}, },
@ -234,10 +314,51 @@ export default {
console.log('挂载'); console.log('挂载');
var info = storage.getVlogUserInfo(); var info = storage.getVlogUserInfo();
if (info != null) { if (info != null) {
console.log('登录了');
this.userId = info.id; this.userId = info.id;
this.conversationList();
} }
}, },
methods: { methods: {
//
async conversationList() {
var data = await conversationData();
console.log(data);
this.converList = data.data.conversationList;
console.log(this.converList);
},
toIm(i) {
if (this.flag) {
this.flag = false;
sendVlogCustomMsg(i, this.vlogItem)
.then((res) => {
console.log('发送成功,返回结果:', res);
uni.showToast({
icon: 'success',
title: '分享成功',
duration: 3000
});
var timer = setTimeout(() => {
clearTimeout(timer);
this.flag = true;
}, 3000);
})
.catch((err) => {
this.flag = true;
console.error('发送失败了', err);
//
uni.showToast({
icon: 'error',
title: '云服务异常'
});
});
} else {
uni.showToast({
icon: 'none',
title: '点太快了'
});
}
},
/** /**
* 选择内容 * 选择内容
*/ */
@ -293,8 +414,9 @@ export default {
copyLink() { copyLink() {
// this.thisVlogId id // this.thisVlogId id
var url = config.shareLink + '/pages/me/vlog?vlogId=' + this.thisVlogId;
uni.setClipboardData({ uni.setClipboardData({
data: this.vlogUrl, data: url,
success: () => { success: () => {
uni.showToast({ uni.showToast({
// //

216
utils/handleim.js Normal file
View File

@ -0,0 +1,216 @@
import {
getUserimInfo
} from '@/api/members';
import {
TUILogin
} from '@tencentcloud/tui-core';
import {
TUIConversationService,
} from '@tencentcloud/chat-uikit-engine';
import {
TUIGlobal
} from '@tencentcloud/universal-api';
import * as Push from '@/uni_modules/TencentCloud-Push';
import storage from "@/utils/storage.js";
// sdkStateNotReady IM断了
// onMessageReceived 收到推送的单聊、群聊、群提示、群系统通知的新消息
// im断开链接时
const onSdkNotReady = function(event) {
console.log('IM断了')
var islogin = storage.getVlogUserInfo();
if (islogin != null) {
// 重新执行IM登录
loginIm()
}
}
const onMessageReceived = function(event) {
// event.data - 存储 Message 对象的数组 - [Message]
// 这里处理消息通知相关业务4.0版本后续进行开发
console.log('收到了消息通知内容')
console.log(event.data)
}
const pushClick = (res) => {
console.log('notification clicked', res);
// 解析扩展信息,跳转到相应的会话(代码仅供参考,发布前需要完善)
try {
const data = JSON.parse(res.data);
const conv_type = data?.entity?.chatType === 1 ? 'C2C' : 'GROUP';
// 根据推送信息拼的 conversationID
const conversationID = `${conv_type}${data.entity.sender}`;
// 切换会话
TUIConversationService.switchConversation(conversationID);
const chatPath = '/TUIKit/components/TUIChat/index';
uni.navigateTo({
url: chatPath
});
} catch (error) {
console.log('error', error);
}
}
const pushOnLine = (res) => {
// res 为消息内容
console.log('在线推送', res);
}
const pushMsgBack = (res) => {
// res 为被撤回的消息 ID
console.log('撤回消息推送', res);
}
export const loginIm = () => {
console.log('执行im登录')
getUserimInfo()
.then(({
data
}) => {
console.log(data)
if (data.code == 200) {
const par = data.result;
TUILogin.login({
SDKAppID: par.sdkAppId,
userID: par.userID,
userSig: par.userSig,
useUploadPlugin: true, // If you need to send rich media messages, please set to true.
framework: `vue2` // framework used vue2 / vue3
}).then((res) => {
var {
SDKAppID,
userID,
userSig,
chat
} = TUILogin.getContext();
getApp().globalData.chat = chat;
console.log('我是个老板', res)
// 每次登录先移除,避免多次监听
chat.off('sdkStateNotReady', onSdkNotReady);
chat.off('onMessageReceived', onMessageReceived);
// 监听im断开链接后重新链接
chat.on('sdkStateNotReady', onSdkNotReady);
// 监听消息通知
chat.on('onMessageReceived', onMessageReceived);
Push.setRegistrationID(par.userID, () => {
console.log('设置id设置id设置id设置id设置id设置id设置id设置id设置id设置id', par.userID);
Push.registerPush(
par.sdkAppId,
'vkFpe55aYqfV7Sk5uGaoxhEstJ3tcI9dquk7JwG1GloDSLD2HeMWeQweWWXgNlhC',
(data) => {
console.log('registerPush ok', data);
Push.getRegistrationID((registrationID) => {
console.log('getRegistrationID ok',
registrationID);
});
},
(errCode, errMsg) => {
console.error('registerPush failed', errCode, errMsg);
}
);
});
// 监听通知栏点击事件,获取推送扩展信息
Push.addPushListener(Push.EVENT.NOTIFICATION_CLICKED, pushClick);
// 监听在线推送
Push.addPushListener(Push.EVENT.MESSAGE_RECEIVED, pushOnLine);
// 监听在线推送被撤回
Push.addPushListener(Push.EVENT.MESSAGE_REVOKED, pushMsgBack);
});
} else {
// 接口返回非 200 状态码,跳转登录页面
uni.navigateTo({
url: '/pages/passport/login'
});
}
})
.catch((e) => {
console.log(e)
});
}
export const clearIm = async () => {
var chat = getApp().globalData.chat;
var res_out = await chat.logout()
console.log(res_out)
console.log('IM退出登录')
getApp().globalData.chat = null;
// chat.logout中做了关闭推送服务
// Push.unRegisterPush().then(res => {
// //反注册关闭推送服务
// console.log(res)
// console.log('反注册关闭推送服务')
// })
Push.removePushListener(Push.EVENT.NOTIFICATION_CLICKED, pushClick)
Push.removePushListener(Push.EVENT.MESSAGE_RECEIVED, pushOnLine)
Push.removePushListener(Push.EVENT.MESSAGE_REVOKED, pushMsgBack)
}
export const conversationData = async () => {
// 会话列表
try {
const chatInstance = getApp().globalData.chat
console.log(chatInstance)
var res = await chatInstance.getConversationList()
return res
} catch (err) {
console.log(err)
}
}
export const sendVlogCustomMsg = async (i, vlogItem) => {
// i=IM相关用户信息
console.log(i);
console.log(vlogItem);
try {
var chat = getApp().globalData.chat;
var conversationType = i.type;
if (conversationType == 'C2C') {
var to = i.userProfile.userID;
} else {
var to = i.groupProfile.groupID;
}
var message = chat.createCustomMessage({
to,
conversationType,
payload: {
data: JSON.stringify({
businessID: 'video',
title: vlogItem.vlogerName,
description: vlogItem.content,
price: '分享好视频',
link: '/pages/me/vlog?vlogId=' + vlogItem.vlogId,
imageUrl: vlogItem.cover || vlogItem.firstFrameImg
}),
description: '[分享视频]',
extension: '',
},
cloudCustomData: JSON.stringify({
pushTitle: vlogItem.vlogerName,
pushDesc: vlogItem.content,
businessID: 'video', // 保持一致
})
})
var result = await chat.sendMessage(message)
console.log('发送成功:', result);
return result; // 成功就把发送结果返回出去
} catch (err) {
console.log(err);
throw err;
}
}

View File

@ -11,6 +11,12 @@ import api from "@/config/api.js";
import uuid from "@/utils/uuid.modified.js"; import uuid from "@/utils/uuid.modified.js";
import {
clearIm
} from "@/utils/handleim.js";
function cleanStorage() { function cleanStorage() {
uni.showToast({ uni.showToast({
title: "你的登录状态已过期,请重新登录", title: "你的登录状态已过期,请重新登录",
@ -21,31 +27,38 @@ function cleanStorage() {
uni.hideLoading(); uni.hideLoading();
} }
storage.setHasLogin(false); storage.setHasLogin(false);
storage.setAccessToken(""); storage.setAccessToken("");
storage.setRefreshToken(""); storage.setRefreshToken("");
storage.setUuid(""); storage.setUuid("");
storage.setUserInfo({}); storage.setUserInfo({});
// 清理vlog信息 // 清理vlog信息
storage.setVlogToken(""); storage.setVlogToken("");
storage.setVlogUserInfo(null); storage.setVlogUserInfo(null);
// 清除初始化数据内容 // 清除初始化数据内容
storage.setRefreshVlogIndex("0"); //不需要刷新 storage.setRefreshVlogIndex("1"); //需要刷新
// 获取当前页面栈 // 退出im登录
const pages = getCurrentPages(); clearIm()
const currentPage = pages[pages.length - 1];
const currentRoute = currentPage.route; // 获取当前页面栈
// 防抖处理跳转 const pages = getCurrentPages();
// #ifdef MP-WEIXIN const currentPage = pages[pages.length - 1];
if (currentRoute !== 'pages/passport/wechatMPLogin') { const currentRoute = currentPage.route;
uni.navigateTo({ url: "/pages/passport/wechatMPLogin" }); // 防抖处理跳转
} // #ifdef MP-WEIXIN
// #endif if (currentRoute !== 'pages/passport/wechatMPLogin') {
// #ifndef MP-WEIXIN uni.navigateTo({
if (currentRoute !== 'pages/passport/login') { url: "/pages/passport/wechatMPLogin"
uni.navigateTo({ url: "/pages/passport/login" }); });
} }
// #endif // #endif
// #ifndef MP-WEIXIN
if (currentRoute !== 'pages/passport/login') {
uni.navigateTo({
url: "/pages/passport/login"
});
}
// #endif
} }
let http = new Request(); let http = new Request();
@ -88,25 +101,25 @@ http.interceptors.request.use(
..._params, ..._params,
}; };
config.params = params; config.params = params;
config.header.accessToken = accessToken; config.header.accessToken = accessToken;
} }
// 配置vlog所需参数 // 配置vlog所需参数
let vlogToken = storage.getVlogToken(); let vlogToken = storage.getVlogToken();
let vlogId = storage.getVlogUserInfo(); let vlogId = storage.getVlogUserInfo();
if (vlogToken) { if (vlogToken) {
config.header.headerUserToken = vlogToken; config.header.headerUserToken = vlogToken;
config.header.headerUserId = vlogId.id; config.header.headerUserId = vlogId.id;
} }
config.header = { config.header = {
...config.header, ...config.header,
uuid: storage.getUuid() || uuid.v1(), uuid: storage.getUuid() || uuid.v1(),
}; };
return config; return config;
}, },
(config) => { (config) => {
return Promise.reject(config); return Promise.reject(config);
} }
); );
// 是否正在刷新的标记 // 是否正在刷新的标记
@ -115,20 +128,28 @@ let isRefreshing = false;
let requests = []; let requests = [];
// 必须使用异步函数,注意 // 必须使用异步函数,注意
http.interceptors.response.use( http.interceptors.response.use(
async (response) => { async (response) => {
// console.log(isRefreshing) // console.log(isRefreshing)
// console.log(response) console.log(response)
/* 请求之后拦截器。可以使用async await 做异步操作 */ /* 请求之后拦截器。可以使用async await 做异步操作 */
// token存在并且token过期 // token存在并且token过期
if (isRefreshing && response.statusCode === 403) {
cleanStorage(); /**
isRefreshing = false; * 后续进来的请求此时异步获取token时isRefreshing一定为true
} * 那么也就代表此时token一定是过期状态响应码也一定为403
* 也就会去清理缓存
* 所以会导致页面多次刷新到登录页
*/
// if (isRefreshing && response.statusCode === 403) {
// cleanStorage();
// isRefreshing = false;
// }
let token = storage.getAccessToken(); let token = storage.getAccessToken();
if ( if (
(token && response.statusCode === 403) || (token && response.statusCode === 403) ||
response.data.status === 403 (token && response.data.status === 403)
) { ) {
if (!isRefreshing) { if (!isRefreshing) {
isRefreshing = true; isRefreshing = true;
@ -149,6 +170,8 @@ http.interceptors.response.use(
return http.request(response.config); return http.request(response.config);
}) })
.catch((err) => { .catch((err) => {
console.log('刷新token失败刷新token失败刷新token失败刷新token失败刷新token失败刷新token失败')
console.log(err);
cleanStorage(); cleanStorage();
return Promise.reject(err); return Promise.reject(err);
}) })
@ -160,39 +183,42 @@ http.interceptors.response.use(
return new Promise((resolve) => { return new Promise((resolve) => {
// 用函数形式将 resolve 存入,等待刷新后再执行 // 用函数形式将 resolve 存入,等待刷新后再执行
requests.push((token) => { requests.push((token) => {
// 刷新token后传入新的token
response.header.accessToken = `${token}`; response.header.accessToken = `${token}`;
resolve(http.request(response.config)); resolve(http.request(response.config));
}); });
}); });
} }
// 如果当前返回没登录 // 这是没有token的情况
} else if ( } else if (
(!token && response.statusCode === 403) || (!token && response.statusCode === 403) ||
response.data.code === 403 response.data.code === 403
) { ) {
console.log('没有token的情况');
cleanStorage(); cleanStorage();
// 如果当前状态码为正常但是success为不正常时 // 如果当前状态码为正常但是success为不正常时
} else if ( } else if (
(response.statusCode == 200 && !response.data.success) || (response.statusCode == 200 && !response.data.success) ||
response.statusCode == 400 response.statusCode == 400
) { ) {
if (response.data.message) { if (response.data.message) {
uni.showToast({ uni.showToast({
title: response.data.message, // title: response.data.message,
icon: "none", title: "请重试",
duration: 1500, icon: "none",
}); duration: 1500,
} });
} else if (response.data.code == 502) { }
cleanStorage(); } else if (response.data.code == 502) {
} cleanStorage();
return response; }
}, return response;
(error) => { },
return error; (error) => {
} return error;
}
); );
export { export {

View File

@ -12,16 +12,16 @@ const CART_BACKBTN = isDev ? "cart_backbtn_dev" : "cart_backbtn";
const AFTERSALE_DATA = isDev ? "aftersale_data_dev" : "aftersale_data"; const AFTERSALE_DATA = isDev ? "aftersale_data_dev" : "aftersale_data";
export default { export default {
setCityCode(val) { setCityCode(val) {
return uni.setStorageSync('cityCode',val) return uni.setStorageSync('cityCode', val)
}, },
getCityCode(){ getCityCode() {
return uni.getStorageSync('cityCode') return uni.getStorageSync('cityCode')
}, },
/** /**
* 写入RefreshVlogIndex * 写入RefreshVlogIndex
*/ */
setRefreshVlogIndex(val) { setRefreshVlogIndex(val) {
return uni.setStorageSync('refreshVlogIndex',val) //0=不需要刷新 return uni.setStorageSync('refreshVlogIndex', val) //0=不需要刷新
}, },
getRefreshVlogIndex() { getRefreshVlogIndex() {
return uni.getStorageSync('refreshVlogIndex') //0=不需要刷新 return uni.getStorageSync('refreshVlogIndex') //0=不需要刷新
@ -48,7 +48,7 @@ export default {
* 获取VlogUserInfo * 获取VlogUserInfo
*/ */
getVlogUserInfo(val) { getVlogUserInfo(val) {
return uni.getStorageSync(VLOG_USER_INFO)||null; return uni.getStorageSync(VLOG_USER_INFO) || null;
}, },
// 写入热门搜索时间戳 // 写入热门搜索时间戳