fix: pk comment

This commit is contained in:
zzc
2026-06-15 22:29:03 +08:00
parent 3c7e520062
commit 88f4220432
3 changed files with 561 additions and 891 deletions

View File

@@ -1,7 +1,7 @@
<template> <template>
<view class="pk-comment-section"> <view class="comment-section" :class="[`comment-section--${variant}`]">
<view class="comment-header"> <view class="comment-header">
<view class="comment-tabs"> <view v-if="showTabs" class="comment-tabs">
<text <text
v-for="tab in tabs" v-for="tab in tabs"
:key="tab.value" :key="tab.value"
@@ -12,23 +12,27 @@
{{ tab.label }} {{ tab.label }}
</text> </text>
</view> </view>
<view class="my-choice-pill" :class="selectedTone ? `my-choice-pill--${selectedTone}` : ''"> <view v-else class="comment-title-wrap">
<text class="my-choice-pill-label">我站</text> <text class="comment-title">{{ sectionTitle }}</text>
<text class="my-choice-pill-value">{{ selectedItemLabel }}</text> </view>
<view v-if="pillValue" class="header-pill" :class="pillTone ? `header-pill--${pillTone}` : ''">
<text v-if="pillLabel" class="header-pill-label">{{ pillLabel }}</text>
<text class="header-pill-value">{{ pillValue }}</text>
</view> </view>
</view> </view>
<view class="compose-card"> <view v-if="allowCompose" class="compose-card">
<view class="compose-tip"> <view class="compose-tip">
<text class="compose-title">说说你的理由</text> <text class="compose-title">{{ composeTitle }}</text>
<text class="compose-desc">支持 {{ selectedItemLabel }} 的观点会更容易引发讨论</text> <text v-if="composeDesc" class="compose-desc">{{ composeDesc }}</text>
</view> </view>
<view class="compose-box"> <view class="compose-box">
<input <input
class="compose-input" class="compose-input"
v-model="commentText" v-model="commentText"
:disabled="sending" :disabled="sending"
placeholder="写下你的 PK 观点..." :placeholder="composePlaceholder"
placeholder-class="compose-placeholder" placeholder-class="compose-placeholder"
confirm-type="send" confirm-type="send"
@confirm="submitMainComment" @confirm="submitMainComment"
@@ -39,32 +43,43 @@
:disabled="sending || !commentText.trim()" :disabled="sending || !commentText.trim()"
@tap="submitMainComment" @tap="submitMainComment"
> >
{{ sending ? "发送中" : "发布" }} {{ sending ? composeSendingText : composeButtonText }}
</button> </button>
</view> </view>
</view> </view>
<view class="comment-list"> <view class="comment-list">
<view v-if="loading && !comments.length" class="comment-state"> <view v-if="loading && !comments.length" class="comment-state">
<text class="comment-state-title">评论加载中...</text> <text class="comment-state-title">{{ loadingTitle }}</text>
<text class="comment-state-desc">看看大家都站哪边</text> <text class="comment-state-desc">{{ loadingDesc }}</text>
</view> </view>
<view v-else-if="loadError && !comments.length" class="comment-state"> <view v-else-if="loadError && !comments.length" class="comment-state">
<text class="comment-state-title">评论加载失败</text> <text class="comment-state-title">{{ errorTitle }}</text>
<text class="comment-state-desc">{{ loadError }}</text> <text class="comment-state-desc">{{ loadError }}</text>
<button class="comment-state-btn" @tap="refreshComments">重新加载</button> <button class="comment-state-btn" @tap="refreshComments">重新加载</button>
</view> </view>
<view v-else-if="!comments.length" class="comment-state">
<text class="comment-state-title">还没有人发言</text> <view v-else-if="!comments.length" class="comment-state comment-state--empty">
<text class="comment-state-desc">你可以成为这场 PK 的第一位评论官</text> <view v-if="showEmptyVisual" class="comment-empty-visual">
<view class="comment-empty-orbit orbit-1"></view>
<view class="comment-empty-orbit orbit-2"></view>
<view class="comment-empty-core">
<text class="comment-empty-emoji">{{ emptyEmoji }}</text>
</view> </view>
</view>
<text class="comment-state-title">{{ emptyTitle }}</text>
<text class="comment-state-desc">{{ emptyDesc }}</text>
<text v-if="emptyTip" class="comment-state-tip">{{ emptyTip }}</text>
</view>
<CommentItem <CommentItem
v-for="comment in comments" v-for="comment in comments"
:key="comment.id" :key="comment.id"
:comment="comment" :comment="comment"
:like-handler="likeComment" :like-handler="likeHandler"
page-name="pk_station" :page-name="pageName"
@need-login="emit('need-login')" @need-login="emitNeedLogin"
@like-change="handleCommentLikeChange" @like-change="handleCommentLikeChange"
@reply="openReplyPopup" @reply="openReplyPopup"
@toggle-replies="handleToggleReplies" @toggle-replies="handleToggleReplies"
@@ -73,15 +88,16 @@
</view> </view>
<view v-if="comments.length" class="comment-footer"> <view v-if="comments.length" class="comment-footer">
<text v-if="loading" class="comment-footer-text">加载中...</text> <text v-if="loading" class="comment-footer-text">{{ footerLoadingText }}</text>
<text <text
v-else-if="hasMore" v-else-if="hasMore && loadMoreMode === 'click'"
class="comment-footer-link" class="comment-footer-link"
@tap="loadComments()" @tap="loadComments()"
> >
查看更多评论 {{ footerMoreText }}
</text> </text>
<text v-else class="comment-footer-text">没有更多评论了</text> <text v-else-if="loadMoreMode === 'scroll'" class="comment-footer-text">{{ footerHintText }}</text>
<text v-else class="comment-footer-text">{{ footerDoneText }}</text>
</view> </view>
<view <view
@@ -119,7 +135,7 @@
:disabled="sendingReply || !replyContent.trim()" :disabled="sendingReply || !replyContent.trim()"
@tap="submitReplyComment" @tap="submitReplyComment"
> >
{{ sendingReply ? "发送中" : "发送" }} {{ sendingReply ? replySendingText : replyButtonText }}
</button> </button>
</view> </view>
</view> </view>
@@ -131,52 +147,185 @@ import { computed, nextTick, ref, watch } from "vue";
import { onUnmounted } from "vue"; import { onUnmounted } from "vue";
import CommentItem from "@/components/CommentItem/CommentItem.vue"; import CommentItem from "@/components/CommentItem/CommentItem.vue";
import { useUserStore } from "@/stores/user"; import { useUserStore } from "@/stores/user";
import {
fetchCommentList,
fetchCommentReplyList,
publishComment,
likeComment,
} from "@/api/pk";
import { FILE_BASE_URL } from "@/utils/constants";
import { formatDate } from "@/utils/date";
const props = defineProps({ const defaultTabs = [
pkId: {
type: String,
default: "",
},
selectedItemId: {
type: String,
default: "",
},
selectedItemLabel: {
type: String,
default: "",
},
currentPair: {
type: Object,
default: null,
},
visible: {
type: Boolean,
default: false,
},
});
const emit = defineEmits(["need-login"]);
const userStore = useUserStore();
const tabs = [
{ label: "最热", value: "hot" }, { label: "最热", value: "hot" },
{ label: "最新", value: "new" }, { label: "最新", value: "new" },
]; ];
const props = defineProps({
requestKey: {
type: String,
default: "",
},
visible: {
type: Boolean,
default: true,
},
variant: {
type: String,
default: "topic",
},
sectionTitle: {
type: String,
default: "评论区",
},
showTabs: {
type: Boolean,
default: true,
},
tabs: {
type: Array,
default: () => defaultTabs,
},
allowCompose: {
type: Boolean,
default: false,
},
composeTitle: {
type: String,
default: "说说你的看法",
},
composeDesc: {
type: String,
default: "",
},
composePlaceholder: {
type: String,
default: "写下你的观点...",
},
composeButtonText: {
type: String,
default: "发布",
},
composeSendingText: {
type: String,
default: "发送中",
},
replyButtonText: {
type: String,
default: "发送",
},
replySendingText: {
type: String,
default: "发送中",
},
pageName: {
type: String,
default: "rating_detail",
},
pillLabel: {
type: String,
default: "",
},
pillValue: {
type: String,
default: "",
},
pillTone: {
type: String,
default: "",
},
loadingTitle: {
type: String,
default: "评论加载中...",
},
loadingDesc: {
type: String,
default: "正在拉取大家的观点",
},
errorTitle: {
type: String,
default: "评论加载失败",
},
errorFallbackText: {
type: String,
default: "网络开了点小差,稍后重试",
},
emptyTitle: {
type: String,
default: "还没有评论",
},
emptyDesc: {
type: String,
default: "来发第一条评论,带动一下讨论气氛",
},
emptyTip: {
type: String,
default: "",
},
emptyEmoji: {
type: String,
default: "💬",
},
showEmptyVisual: {
type: Boolean,
default: false,
},
footerLoadingText: {
type: String,
default: "加载中...",
},
footerMoreText: {
type: String,
default: "查看更多评论",
},
footerDoneText: {
type: String,
default: "没有更多评论了",
},
footerHintText: {
type: String,
default: "上拉加载更多",
},
loadMoreMode: {
type: String,
default: "click",
},
showSuccessToast: {
type: Boolean,
default: true,
},
mainSuccessText: {
type: String,
default: "评论已发布",
},
replySuccessText: {
type: String,
default: "回复已发送",
},
listHandler: {
type: Function,
required: true,
},
repliesHandler: {
type: Function,
required: true,
},
publishHandler: {
type: Function,
required: true,
},
normalizeComment: {
type: Function,
required: true,
},
likeHandler: {
type: Function,
default: null,
},
});
const emit = defineEmits(["need-login", "published"]);
const userStore = useUserStore();
const comments = ref([]); const comments = ref([]);
const currentTab = ref("hot"); const currentTab = ref(defaultTabs[0].value);
const currentPage = ref(1); const currentPage = ref(1);
const hasMore = ref(true); const hasMore = ref(true);
const loading = ref(false); const loading = ref(false);
const sending = ref(false); const sending = ref(false);
const sendingReply = ref(false);
const loadError = ref(""); const loadError = ref("");
const commentText = ref(""); const commentText = ref("");
const replyTarget = ref(null); const replyTarget = ref(null);
@@ -184,86 +333,59 @@ const replyPopupVisible = ref(false);
const replyInputFocus = ref(false); const replyInputFocus = ref(false);
const replyContent = ref(""); const replyContent = ref("");
const replyKeyboardHeight = ref(0); const replyKeyboardHeight = ref(0);
const sendingReply = ref(false);
let keyboardHeightListener = null; let keyboardHeightListener = null;
const selectedTone = computed(() => {
if (!props.currentPair || !props.selectedItemId) return "";
if (props.selectedItemId === props.currentPair.left?.id) return "left";
if (props.selectedItemId === props.currentPair.right?.id) return "right";
return "";
});
const isLoggedIn = computed(() => !!userStore.token || !!userStore.userInfo?.nickName); const isLoggedIn = computed(() => !!userStore.token || !!userStore.userInfo?.nickName);
const replyPlaceholder = computed(() => { const replyPlaceholder = computed(() => {
return replyTarget.value?.replyToName return replyTarget.value?.replyToName ? `回复 @${replyTarget.value.replyToName}...` : "写下你的回复";
? `回复 @${replyTarget.value.replyToName}...`
: "写下你的回复";
}); });
const buildAvatarUrl = (avatar) => { const parseListResponse = (res) => {
if (!avatar) return "https://api.dicebear.com/7.x/avataaars/svg?seed=fallback"; const source = res?.data || res || {};
const normalizedAvatar = String(avatar).trim(); const rawList =
return normalizedAvatar.startsWith("http") ? normalizedAvatar : `${FILE_BASE_URL}${normalizedAvatar}`; source.list ||
source.records ||
res?.list ||
res?.records ||
(Array.isArray(source) ? source : []);
return Array.isArray(rawList) ? rawList : [];
}; };
const resolveChoiceMeta = (chooseItemId) => { const resolveHasMore = (res, list, page) => {
if (!chooseItemId || !props.currentPair) { const data = res?.data || res || {};
return { choiceLabel: "", choiceTone: "" }; const hasNext = data?.hasNext ?? res?.hasNext;
if (typeof hasNext === "boolean") return hasNext;
const total = Number(data?.totalCount ?? data?.total ?? res?.totalCount ?? res?.total ?? 0);
if (total > 0) {
const safeSize = Math.max(list.length, 1);
return page * safeSize < total;
} }
if (chooseItemId === props.currentPair.left?.id) {
return { const pages = Number(data?.pages || res?.pages || 0);
choiceLabel: `支持 ${props.currentPair.left.name}`, if (pages > 0) return page < pages;
choiceTone: "left",
}; return list.length > 0;
}
if (chooseItemId === props.currentPair.right?.id) {
return {
choiceLabel: `支持 ${props.currentPair.right.name}`,
choiceTone: "right",
};
}
return { choiceLabel: "已站队", choiceTone: "" };
}; };
const normalizeComment = (item = {}, rootComment = null) => { const emitNeedLogin = () => {
const user = item.user || {}; emit("need-login");
const replyToUser = item.replyToUser || {}; };
const choiceMeta = resolveChoiceMeta(item.chooseItemId);
return { const ensureLogin = () => {
id: item.id, if (isLoggedIn.value) return true;
rootCommentId: item.rootCommentId || rootComment?.id || null, emitNeedLogin();
parentCommentId: item.parentCommentId || rootComment?.id || null, return false;
replyToCommentId: item.replyToCommentId || null,
name: user.nickname || "匿名用户",
avatar: buildAvatarUrl(user.avatar),
time: formatDate(item.createdAt) || "刚刚",
content: item.content || "",
likes: Number(item.likeCount || 0),
isLiked: !!item.isLiked,
userAction: "",
replyCount: Number(item.replyCount || 0),
replyToName: replyToUser.nickname || "",
choiceLabel: choiceMeta.choiceLabel,
choiceTone: choiceMeta.choiceTone,
chooseItemId: item.chooseItemId || "",
repliesLoading: false,
repliesLoaded: false,
repliesHasMore: false,
repliesPage: 1,
replies: [],
};
}; };
const resetState = () => { const resetState = () => {
comments.value = []; comments.value = [];
currentTab.value = "hot";
currentPage.value = 1; currentPage.value = 1;
hasMore.value = true; hasMore.value = true;
loading.value = false; loading.value = false;
sending.value = false; sending.value = false;
sendingReply.value = false;
loadError.value = ""; loadError.value = "";
commentText.value = ""; commentText.value = "";
closeReplyPopup(); closeReplyPopup();
@@ -276,24 +398,8 @@ const patchCommentItem = (commentId, updater) => {
}); });
}; };
const resolveHasMore = (res, list, page) => {
const data = res?.data || res || {};
const hasNext = data?.hasNext ?? res?.hasNext;
if (typeof hasNext === "boolean") return hasNext;
const total = Number(data?.totalCount ?? data?.total ?? res?.totalCount ?? res?.total ?? 0);
if (total > 0) {
return page * Math.max(1, list.length) < total;
}
const pages = Number(data?.pages || res?.pages || 0);
if (pages > 0) return page < pages;
return list.length > 0;
};
const loadComments = async ({ reset = false } = {}) => { const loadComments = async ({ reset = false } = {}) => {
if (!props.visible || !props.pkId || loading.value) return; if (!props.visible || !props.requestKey || loading.value) return;
if (!reset && !hasMore.value) return; if (!reset && !hasMore.value) return;
const page = reset ? 1 : currentPage.value; const page = reset ? 1 : currentPage.value;
@@ -301,26 +407,18 @@ const loadComments = async ({ reset = false } = {}) => {
try { try {
loading.value = true; loading.value = true;
loadError.value = ""; loadError.value = "";
const res = await fetchCommentList({ const res = await props.listHandler({
pkId: props.pkId,
page, page,
orderBy: currentTab.value, orderBy: currentTab.value,
}); });
const source = res?.data || res || {}; const list = parseListResponse(res);
const rawList = const normalized = list.map((item) => props.normalizeComment(item));
source.list ||
source.records ||
res?.list ||
res?.records ||
(Array.isArray(source) ? source : []);
const list = Array.isArray(rawList) ? rawList : [];
const normalized = list.map((item) => normalizeComment(item));
comments.value = reset ? normalized : [...comments.value, ...normalized]; comments.value = reset ? normalized : [...comments.value, ...normalized];
hasMore.value = resolveHasMore(res, list, page); hasMore.value = resolveHasMore(res, list, page);
currentPage.value = page + 1; currentPage.value = page + 1;
} catch (error) { } catch (error) {
loadError.value = "网络开了点小差,稍后重试"; loadError.value = props.errorFallbackText;
} finally { } finally {
loading.value = false; loading.value = false;
} }
@@ -332,6 +430,11 @@ const refreshComments = async () => {
await loadComments({ reset: true }); await loadComments({ reset: true });
}; };
const loadMoreComments = async () => {
if (loading.value || !hasMore.value) return;
await loadComments();
};
const switchTab = (tab) => { const switchTab = (tab) => {
if (currentTab.value === tab) return; if (currentTab.value === tab) return;
currentTab.value = tab; currentTab.value = tab;
@@ -339,22 +442,26 @@ const switchTab = (tab) => {
}; };
const submitMainComment = async () => { const submitMainComment = async () => {
if (!isLoggedIn.value) { if (!ensureLogin()) return;
emit("need-login");
return;
}
const content = commentText.value.trim(); const content = commentText.value.trim();
if (!content || sending.value || !props.pkId || !props.selectedItemId) return; if (!content || sending.value) return;
try { try {
sending.value = true; sending.value = true;
await publishComment({ await props.publishHandler({
pkId: props.pkId,
chooseItemId: props.selectedItemId,
content, content,
mode: "comment",
replyTarget: null,
}); });
uni.showToast({ title: "评论已发布", icon: "none" }); if (props.showSuccessToast) {
uni.showToast({ title: props.mainSuccessText, icon: "none" });
}
commentText.value = ""; commentText.value = "";
emit("published", {
mode: "comment",
content,
replyTarget: null,
});
await refreshComments(); await refreshComments();
} catch (error) { } catch (error) {
uni.showToast({ title: "发布失败", icon: "none" }); uni.showToast({ title: "发布失败", icon: "none" });
@@ -364,10 +471,7 @@ const submitMainComment = async () => {
}; };
const openReplyPopup = async (payload) => { const openReplyPopup = async (payload) => {
if (!isLoggedIn.value) { if (!ensureLogin()) return;
emit("need-login");
return;
}
replyTarget.value = payload; replyTarget.value = payload;
replyPopupVisible.value = true; replyPopupVisible.value = true;
await nextTick(); await nextTick();
@@ -385,24 +489,27 @@ const closeReplyPopup = () => {
}; };
const submitReplyComment = async () => { const submitReplyComment = async () => {
if (!isLoggedIn.value) { if (!ensureLogin()) return;
emit("need-login");
return;
}
const content = replyContent.value.trim(); const content = replyContent.value.trim();
if (!content || !replyTarget.value || sendingReply.value || !props.pkId || !props.selectedItemId) return; if (!content || !replyTarget.value || sendingReply.value) return;
try { try {
sendingReply.value = true; sendingReply.value = true;
await publishComment({ await props.publishHandler({
pkId: props.pkId,
chooseItemId: props.selectedItemId,
content, content,
parentCommentId: replyTarget.value.parentCommentId, mode: "reply",
replyToCommentId: replyTarget.value.replyToCommentId, replyTarget: replyTarget.value,
}); });
uni.showToast({ title: "回复已发送", icon: "none" }); if (props.showSuccessToast) {
uni.showToast({ title: props.replySuccessText, icon: "none" });
}
const publishedReplyTarget = replyTarget.value;
closeReplyPopup(); closeReplyPopup();
emit("published", {
mode: "reply",
content,
replyTarget: publishedReplyTarget,
});
await refreshComments(); await refreshComments();
} catch (error) { } catch (error) {
uni.showToast({ title: "回复失败", icon: "none" }); uni.showToast({ title: "回复失败", icon: "none" });
@@ -412,7 +519,7 @@ const submitReplyComment = async () => {
}; };
const loadReplies = async (comment, page = 1) => { const loadReplies = async (comment, page = 1) => {
if (!comment?.id || !props.pkId) return; if (!comment?.id) return;
patchCommentItem(comment.id, (item) => ({ patchCommentItem(comment.id, (item) => ({
...item, ...item,
@@ -420,15 +527,12 @@ const loadReplies = async (comment, page = 1) => {
})); }));
try { try {
const res = await fetchCommentReplyList({ const res = await props.repliesHandler({
pkId: props.pkId,
rootCommentId: comment.id, rootCommentId: comment.id,
page, page,
}); });
const source = res?.data || res || {}; const list = parseListResponse(res);
const rawList = source.list || res?.list || []; const normalizedReplies = list.map((reply) => props.normalizeComment(reply, comment));
const list = Array.isArray(rawList) ? rawList : [];
const normalizedReplies = list.map((reply) => normalizeComment(reply, comment));
const hasMoreReplies = resolveHasMore(res, list, page); const hasMoreReplies = resolveHasMore(res, list, page);
patchCommentItem(comment.id, (item) => ({ patchCommentItem(comment.id, (item) => ({
@@ -486,9 +590,9 @@ const handleCommentLikeChange = ({ id, parentId, isReply, isLiked, likes }) => {
}; };
watch( watch(
() => [props.pkId, props.visible, props.selectedItemId], () => [props.requestKey, props.visible],
([pkId, visible, selectedItemId]) => { ([requestKey, visible]) => {
if (!pkId || !visible || !selectedItemId) { if (!requestKey || !visible) {
resetState(); resetState();
return; return;
} }
@@ -500,16 +604,6 @@ watch(
{ immediate: true } { immediate: true }
); );
watch(
() => props.currentPair,
() => {
comments.value = comments.value.map((comment) => ({
...comment,
...resolveChoiceMeta(comment.chooseItemId),
}));
}
);
if (uni.onKeyboardHeightChange) { if (uni.onKeyboardHeightChange) {
keyboardHeightListener = (res) => { keyboardHeightListener = (res) => {
replyKeyboardHeight.value = res?.height || 0; replyKeyboardHeight.value = res?.height || 0;
@@ -525,12 +619,12 @@ onUnmounted(() => {
defineExpose({ defineExpose({
refreshComments, refreshComments,
loadMoreComments,
}); });
</script> </script>
<style lang="scss" scoped> <style lang="scss" scoped>
.pk-comment-section { .comment-section {
margin-top: 24rpx;
padding: 32rpx; padding: 32rpx;
border-radius: 32rpx; border-radius: 32rpx;
background: rgba(255, 255, 255, 0.94); background: rgba(255, 255, 255, 0.94);
@@ -538,6 +632,14 @@ defineExpose({
box-shadow: 0 18rpx 42rpx rgba(87, 92, 145, 0.08); box-shadow: 0 18rpx 42rpx rgba(87, 92, 145, 0.08);
} }
.comment-section--topic {
margin-top: 0;
}
.comment-section--pk {
margin-top: 24rpx;
}
.comment-header { .comment-header {
display: flex; display: flex;
align-items: center; align-items: center;
@@ -551,6 +653,17 @@ defineExpose({
gap: 34rpx; gap: 34rpx;
} }
.comment-title-wrap {
display: flex;
align-items: center;
}
.comment-title {
font-size: 32rpx;
font-weight: 800;
color: #1f2432;
}
.comment-tab { .comment-tab {
font-size: 30rpx; font-size: 30rpx;
color: #8a90a0; color: #8a90a0;
@@ -576,7 +689,7 @@ defineExpose({
background: linear-gradient(90deg, #6557ff, #4d44f1); background: linear-gradient(90deg, #6557ff, #4d44f1);
} }
.my-choice-pill { .header-pill {
flex-shrink: 0; flex-shrink: 0;
display: inline-flex; display: inline-flex;
align-items: center; align-items: center;
@@ -586,22 +699,22 @@ defineExpose({
background: rgba(92, 67, 245, 0.1); background: rgba(92, 67, 245, 0.1);
} }
.my-choice-pill--right { .header-pill--right {
background: rgba(255, 141, 95, 0.12); background: rgba(255, 141, 95, 0.12);
} }
.my-choice-pill-label { .header-pill-label {
font-size: 22rpx; font-size: 22rpx;
color: #8a90a0; color: #8a90a0;
} }
.my-choice-pill-value { .header-pill-value {
font-size: 22rpx; font-size: 22rpx;
font-weight: 700; font-weight: 700;
color: #4d44f1; color: #4d44f1;
} }
.my-choice-pill--right .my-choice-pill-value { .header-pill--right .header-pill-value {
color: #ff7a45; color: #ff7a45;
} }
@@ -693,6 +806,53 @@ defineExpose({
background: #f8f9ff; background: #f8f9ff;
} }
.comment-state--empty {
background: linear-gradient(180deg, rgba(248, 249, 255, 0.92) 0%, rgba(255, 255, 255, 0.96) 100%);
}
.comment-empty-visual {
position: relative;
width: 176rpx;
height: 176rpx;
display: flex;
align-items: center;
justify-content: center;
margin-bottom: 24rpx;
}
.comment-empty-core {
position: relative;
z-index: 2;
width: 112rpx;
height: 112rpx;
border-radius: 50%;
background: linear-gradient(135deg, #ffffff 0%, #eef2ff 100%);
box-shadow: 0 16rpx 34rpx rgba(99, 102, 241, 0.14);
display: flex;
align-items: center;
justify-content: center;
}
.comment-empty-emoji {
font-size: 50rpx;
}
.comment-empty-orbit {
position: absolute;
border-radius: 50%;
border: 2rpx dashed rgba(99, 102, 241, 0.16);
}
.orbit-1 {
inset: 12rpx;
}
.orbit-2 {
inset: 32rpx;
border-style: solid;
border-color: rgba(129, 140, 248, 0.12);
}
.comment-state-title { .comment-state-title {
display: block; display: block;
font-size: 30rpx; font-size: 30rpx;
@@ -708,6 +868,14 @@ defineExpose({
line-height: 1.7; line-height: 1.7;
} }
.comment-state-tip {
display: block;
margin-top: 12rpx;
font-size: 22rpx;
color: #a0a6b5;
line-height: 1.7;
}
.comment-state-btn { .comment-state-btn {
margin-top: 22rpx; margin-top: 22rpx;
height: 72rpx; height: 72rpx;

View File

@@ -79,15 +79,31 @@
</view> </view>
</view> </view>
<PkCommentSection <CommentSection
v-if="currentPair && hasVoted" v-if="currentPair && hasVoted"
ref="commentSectionRef" ref="commentSectionRef"
:pk-id="currentPair.id" variant="pk"
:current-pair="currentPair" :request-key="commentRequestKey"
:selected-item-id="selectedItemId"
:selected-item-label="selectedItemLabel"
:visible="hasVoted" :visible="hasVoted"
:allow-compose="true"
compose-title="说说你的理由"
:compose-desc="`支持 ${selectedItemLabel} 的观点会更容易引发讨论`"
compose-placeholder="写下你的 PK 观点..."
page-name="pk_station"
pill-label="我站"
:pill-value="selectedItemLabel"
:pill-tone="selectedTone"
loading-desc="看看大家都站哪边"
empty-title="还没有人发言"
empty-desc="你可以成为这场 PK 的第一位评论官"
footer-more-text="查看更多评论"
:list-handler="fetchPkCommentList"
:replies-handler="fetchPkCommentReplies"
:publish-handler="publishPkComment"
:normalize-comment="normalizePkComment"
:like-handler="likeComment"
@need-login="openLoginPopup('请先登录后再参与评论')" @need-login="openLoginPopup('请先登录后再参与评论')"
@published="handleCommentPublished"
/> />
<view v-else-if="!currentPair" class="state-card"> <view v-else-if="!currentPair" class="state-card">
@@ -105,9 +121,10 @@
import { computed, ref } from "vue"; import { computed, ref } from "vue";
import { onLoad, onPullDownRefresh, onShareAppMessage, onShareTimeline } from "@dcloudio/uni-app"; import { onLoad, onPullDownRefresh, onShareAppMessage, onShareTimeline } from "@dcloudio/uni-app";
import { getStatusBarHeight } from "@/utils/system"; import { getStatusBarHeight } from "@/utils/system";
import { fetchRandomTopicList, vote } from "@/api/pk"; import { fetchRandomTopicList, vote, fetchCommentList, fetchCommentReplyList, publishComment, likeComment } from "@/api/pk";
import { FILE_BASE_URL } from "@/utils/constants"; import { FILE_BASE_URL } from "@/utils/constants";
import PkCommentSection from "@/components/PkCommentSection/PkCommentSection.vue"; import { formatDate } from "@/utils/date";
import CommentSection from "@/components/CommentSection/CommentSection.vue";
import LoginPopup from "@/components/LoginPopup/LoginPopup.vue"; import LoginPopup from "@/components/LoginPopup/LoginPopup.vue";
import { useUserStore } from "@/stores/user"; import { useUserStore } from "@/stores/user";
import { getShareReward } from "@/api/system"; import { getShareReward } from "@/api/system";
@@ -133,12 +150,92 @@ const selectedItemLabel = computed(() => {
if (!currentPair.value || !selectedSide.value) return ""; if (!currentPair.value || !selectedSide.value) return "";
return selectedSide.value === "left" ? currentPair.value.left.name : currentPair.value.right.name; return selectedSide.value === "left" ? currentPair.value.left.name : currentPair.value.right.name;
}); });
const selectedTone = computed(() => {
if (!selectedSide.value) return "";
return selectedSide.value === "left" ? "left" : "right";
});
const commentRequestKey = computed(() => {
if (!currentPair.value?.id || !selectedItemId.value) return "";
return `${currentPair.value.id}_${selectedItemId.value}`;
});
const buildAvatarUrl = (avatar) => { const buildAvatarUrl = (avatar) => {
if (!avatar) return "https://api.dicebear.com/7.x/avataaars/svg?seed=fallback"; if (!avatar) return "https://api.dicebear.com/7.x/avataaars/svg?seed=fallback";
return String(avatar).startsWith("http") ? avatar : `${FILE_BASE_URL}${avatar}`; const normalizedAvatar = String(avatar).trim();
return normalizedAvatar.startsWith("http") ? normalizedAvatar : `${FILE_BASE_URL}${normalizedAvatar}`;
}; };
const resolveChoiceMeta = (chooseItemId) => {
if (!chooseItemId || !currentPair.value) {
return { choiceLabel: "", choiceTone: "" };
}
if (chooseItemId === currentPair.value.left?.id) {
return { choiceLabel: `支持 ${currentPair.value.left.name}`, choiceTone: "left" };
}
if (chooseItemId === currentPair.value.right?.id) {
return { choiceLabel: `支持 ${currentPair.value.right.name}`, choiceTone: "right" };
}
return { choiceLabel: "已站队", choiceTone: "" };
};
const normalizePkComment = (item = {}, rootComment = null) => {
const user = item.user || {};
const replyToUser = item.replyToUser || {};
const choiceMeta = resolveChoiceMeta(item.chooseItemId);
return {
id: item.id,
rootCommentId: item.rootCommentId || rootComment?.id || null,
parentCommentId: item.parentCommentId || rootComment?.id || null,
replyToCommentId: item.replyToCommentId || null,
name: user.nickname || "匿名用户",
avatar: buildAvatarUrl(user.avatar),
time: formatDate(item.createdAt) || "刚刚",
content: item.content || "",
likes: Number(item.likeCount || 0),
isLiked: !!item.isLiked,
userAction: "",
replyCount: Number(item.replyCount || 0),
replyToName: replyToUser.nickname || "",
choiceLabel: choiceMeta.choiceLabel,
choiceTone: choiceMeta.choiceTone,
chooseItemId: item.chooseItemId || "",
repliesLoading: false,
repliesLoaded: false,
repliesHasMore: false,
repliesPage: 1,
replies: [],
};
};
const fetchPkCommentList = ({ page, orderBy }) => {
return fetchCommentList({
pkId: currentPair.value?.id,
page,
orderBy,
});
};
const fetchPkCommentReplies = ({ rootCommentId, page }) => {
return fetchCommentReplyList({
pkId: currentPair.value?.id,
rootCommentId,
page,
});
};
const publishPkComment = ({ content, replyTarget, mode }) => {
return publishComment({
pkId: currentPair.value?.id,
chooseItemId: selectedItemId.value,
content,
parentCommentId: mode === "reply" ? replyTarget?.parentCommentId : undefined,
replyToCommentId: mode === "reply" ? replyTarget?.replyToCommentId : undefined,
});
};
const handleCommentPublished = () => {};
const normalizePercent = (value) => { const normalizePercent = (value) => {
const number = Number(value); const number = Number(value);
if (!Number.isFinite(number)) return null; if (!Number.isFinite(number)) return null;

View File

@@ -84,109 +84,44 @@
</view> --> </view> -->
<!-- 评论区 --> <!-- 评论区 -->
<view class="comments-section card"> <CommentSection
<view class="tabs-header"> ref="commentSectionRef"
<view class="tabs"> variant="topic"
<text class="tab" :class="{ active: currentTab === 'hot' }" @tap="switchTab('hot')">最热</text> section-title="评论区"
<text class="tab" :class="{ active: currentTab === 'new' }" @tap="switchTab('new')">最新</text> :request-key="commentRequestKey"
</view> :visible="!!commentRequestKey"
<!-- <text class="filter-icon"></text> --> :allow-compose="false"
</view> page-name="rating_detail"
loading-desc="正在拉取大家的锐评"
<view class="comment-list"> empty-title="还没有评论"
<view v-if="commentLoading && !comments.length" class="comment-state"> empty-desc="来发第一条锐评带动一下讨论气氛"
<text class="comment-state-title">评论加载中...</text> empty-tip="你的观点可能就是这条榜单最有意思的开始"
<text class="comment-state-desc">正在拉取大家的锐评</text> :show-empty-visual="true"
</view> load-more-mode="scroll"
<view v-else-if="commentError && !comments.length" class="comment-state"> footer-hint-text="上拉加载更多"
<text class="comment-state-title">评论加载失败</text> :show-success-toast="false"
<text class="comment-state-desc">{{ commentError }}</text> :list-handler="fetchTopicComments"
<button class="comment-state-btn" @tap="retryLoadComments">重新加载</button> :replies-handler="fetchTopicCommentReplies"
</view> :publish-handler="publishTopicComment"
<view v-else-if="!comments.length" class="comment-state"> :normalize-comment="normalizeCommentItem"
<view class="comment-empty-visual">
<view class="comment-empty-orbit orbit-1"></view>
<view class="comment-empty-orbit orbit-2"></view>
<view class="comment-empty-core">
<text class="comment-empty-emoji">💬</text>
</view>
</view>
<text class="comment-state-title">还没有评论</text>
<text class="comment-state-desc">来发第一条锐评带动一下讨论气氛</text>
<text class="comment-state-tip">你的观点可能就是这条榜单最有意思的开始</text>
</view>
<CommentItem
v-for="(comment, index) in comments"
:key="comment.id"
:comment="comment"
@need-login="openLoginPopup" @need-login="openLoginPopup"
@like-change="handleCommentLikeChange" @published="handleCommentPublished"
@reply="handleReplyComment"
@toggle-replies="handleToggleReplies"
@more-replies="handleLoadMoreReplies"
/> />
</view> </view>
<!-- 加载更多 -->
<view v-if="comments.length" class="load-more">
<text>{{ commentLoadText }}</text>
</view>
</view>
</view>
<!-- 评分成功特效弹窗 --> <!-- 评分成功特效弹窗 -->
<view
v-if="replyPopupVisible"
class="reply-popup-mask"
@tap="closeReplyPopup"
></view>
<view
v-if="replyPopupVisible"
class="reply-popup"
:style="{ bottom: `${replyKeyboardHeight}px` }"
>
<view class="reply-popup-header">
<view class="reply-popup-user">
<text class="reply-popup-label">回复</text>
<text class="reply-popup-name">@{{ replyTarget?.replyToName || 'Ta' }}</text>
</view>
<text class="reply-popup-close" @tap="closeReplyPopup">取消</text>
</view>
<view class="reply-popup-input-wrap">
<input
class="reply-popup-input"
v-model="replyContent"
:focus="replyInputFocus"
:disabled="isSendingReply"
:adjust-position="false"
confirm-type="send"
:placeholder="replyPlaceholder"
placeholder-class="reply-popup-placeholder"
@confirm="handleSendReply"
/>
<button
class="reply-popup-send"
:class="{ disabled: isSendingReply || !replyContent.trim() }"
:disabled="isSendingReply || !replyContent.trim()"
@tap="handleSendReply"
>
{{ isSendingReply ? '发送中' : '发送' }}
</button>
</view>
</view>
<SuccessPopup ref="successPopupRef" /> <SuccessPopup ref="successPopupRef" />
<LoginPopup ref="loginPopupRef" @logind="handleLoginSuccess" /> <LoginPopup ref="loginPopupRef" @logind="handleLoginSuccess" />
</view> </view>
</template> </template>
<script setup> <script setup>
import { computed, nextTick, ref } from 'vue'; import { computed, ref } from 'vue';
import { getStatusBarHeight } from "@/utils/system"; import { getStatusBarHeight } from "@/utils/system";
import { onLoad, onPullDownRefresh, onReachBottom, onShareAppMessage, onShareTimeline, onUnload } from "@dcloudio/uni-app"; import { onLoad, onPullDownRefresh, onReachBottom, onShareAppMessage, onShareTimeline } from "@dcloudio/uni-app";
import AttitudePanel from "@/components/AttitudePanel/AttitudePanel.vue"; import AttitudePanel from "@/components/AttitudePanel/AttitudePanel.vue";
import SuccessPopup from "@/components/SuccessPopup/SuccessPopup.vue"; import SuccessPopup from "@/components/SuccessPopup/SuccessPopup.vue";
import CommentItem from "@/components/CommentItem/CommentItem.vue"; import CommentSection from "@/components/CommentSection/CommentSection.vue";
import LoginPopup from "@/components/LoginPopup/LoginPopup.vue"; import LoginPopup from "@/components/LoginPopup/LoginPopup.vue";
import { FILE_BASE_URL } from "@/utils/constants"; import { FILE_BASE_URL } from "@/utils/constants";
import { fetchTopicRatingItems as fetchTopicItemList } from "@/api/topic"; import { fetchTopicRatingItems as fetchTopicItemList } from "@/api/topic";
@@ -197,22 +132,17 @@ import { getShareReward } from "@/api/system";
import { useUserStore } from "@/stores/user"; import { useUserStore } from "@/stores/user";
const userStore = useUserStore(); const userStore = useUserStore();
const statusBarHeight = ref(getStatusBarHeight() || 44); const statusBarHeight = ref(getStatusBarHeight() || 44);
const hasMore = ref(true);
const currentPage = ref(1);
const currentAction = ref(''); const currentAction = ref('');
const successPopupRef = ref(null); const successPopupRef = ref(null);
const loginPopupRef = ref(null); const loginPopupRef = ref(null);
const attitudePanelRef = ref(null); const attitudePanelRef = ref(null);
const currentTab = ref('hot'); // 'hot' 或 'new' const commentSectionRef = ref(null);
const isLoggedIn = computed(() => !!userStore.token || !!userStore.userInfo?.nickName); const isLoggedIn = computed(() => !!userStore.token || !!userStore.userInfo?.nickName);
const commentLoading = ref(false);
const isSendingComment = ref(false); const isSendingComment = ref(false);
const commentError = ref('');
const pkPreview = ref(null); const pkPreview = ref(null);
const commentLoadText = computed(() => { const commentRequestKey = computed(() => {
if (commentLoading.value && comments.value.length) return '加载中...'; if (!detailData.value.topicId || !itemId.value) return '';
if (!hasMore.value) return '没有更多了'; return `${detailData.value.topicId}_${itemId.value}`;
return '上拉加载更多';
}); });
const goBack = () => { const goBack = () => {
@@ -238,16 +168,7 @@ const detailData = ref({
userAction: "", userAction: "",
topicId: '' topicId: ''
}); });
const comments = ref([]);
const itemId = ref(''); const itemId = ref('');
const replyTarget = ref(null);
const replyPopupVisible = ref(false);
const replyInputFocus = ref(false);
const replyContent = ref('');
const replyKeyboardHeight = ref(0);
const isSendingReply = ref(false);
let keyboardHeightListener = null;
const buildAvatarUrl = (avatar) => { const buildAvatarUrl = (avatar) => {
if (!avatar) return 'https://api.dicebear.com/7.x/avataaars/svg?seed=fallback'; if (!avatar) return 'https://api.dicebear.com/7.x/avataaars/svg?seed=fallback';
@@ -282,71 +203,6 @@ const normalizeCommentItem = (item = {}, rootComment = null) => {
}; };
}; };
const clearReplyTarget = () => {
replyTarget.value = null;
};
const replyPlaceholder = computed(() => {
return replyTarget.value?.replyToName
? `回复 @${replyTarget.value.replyToName}...`
: '回复一下这条评论';
});
const patchCommentItem = (commentId, updater) => {
comments.value = comments.value.map((comment) => {
if (comment.id !== commentId) return comment;
return updater(comment);
});
};
const resolveReplyHasMore = (res, list, currentPage) => {
const data = res?.data || res || {};
const hasNext = data?.hasNext || res?.hasNext;
if (typeof hasNext === 'boolean') return hasNext;
const pages = Number(data?.pages || res?.pages || 0);
if (pages > 0) return currentPage < pages;
const total = Number(data?.totalCount || data?.total || res?.totalCount || res?.total || 0);
if (total > 0) {
return currentPage * list.length < total || list.length < total;
}
return list.length > 0;
};
const openReplyPopup = async () => {
replyPopupVisible.value = true;
await nextTick();
replyInputFocus.value = false;
await nextTick();
replyInputFocus.value = true;
};
const closeReplyPopup = () => {
replyPopupVisible.value = false;
replyInputFocus.value = false;
replyKeyboardHeight.value = 0;
replyContent.value = '';
clearReplyTarget();
};
const handleReplyComment = (payload) => {
if (!isLoggedIn.value) {
openLoginPopup();
return;
}
replyTarget.value = {
rootCommentId: payload.rootCommentId,
parentCommentId: payload.parentCommentId,
replyToCommentId: payload.replyToCommentId,
replyToName: payload.replyToName || '',
content: payload.content || ''
};
openReplyPopup();
};
const calcPkPercent = (leftScore, rightScore) => { const calcPkPercent = (leftScore, rightScore) => {
const left = Number(leftScore) || 0; const left = Number(leftScore) || 0;
const right = Number(rightScore) || 0; const right = Number(rightScore) || 0;
@@ -462,41 +318,35 @@ const handleActionChange = async (action) => {
} }
}; };
const submitComment = async ({ content, parentCommentId, replyToCommentId, successMode = 'comment' }) => { const publishTopicComment = ({ content, replyTarget, mode }) => {
if (!isLoggedIn.value) { return topicItemComment({
openLoginPopup();
return;
}
if (!detailData.value.topicId || !itemId.value) return false;
try {
if (successMode === 'reply') {
isSendingReply.value = true;
} else {
isSendingComment.value = true;
}
uni.showLoading({ title: '发送中...' });
await topicItemComment({
topicId: detailData.value.topicId, topicId: detailData.value.topicId,
itemId: itemId.value, itemId: itemId.value,
content, content,
parentCommentId: parentCommentId || undefined, parentCommentId: mode === 'reply' ? replyTarget?.parentCommentId : undefined,
replyToCommentId: replyToCommentId || undefined replyToCommentId: mode === 'reply' ? replyTarget?.replyToCommentId : undefined
}); });
uni.hideLoading(); };
// 弹出成功弹窗 const fetchTopicComments = ({ page, orderBy }) => {
return topicItemCommentList(detailData.value.topicId, itemId.value, page, orderBy);
};
const fetchTopicCommentReplies = ({ rootCommentId, page }) => {
return topicItemCommentReplyList({
rootCommentId,
page
});
};
const handleCommentPublished = ({ mode, content, replyTarget }) => {
if (successPopupRef.value) { if (successPopupRef.value) {
successPopupRef.value.show({ successPopupRef.value.show({
emoji: '💬', emoji: '💬',
label: successMode === 'reply' ? '回复已发送' : '你的锐评已发布' label: mode === 'reply' ? '回复已发送' : '你的锐评已发布'
}, 'comment'); }, 'comment');
} }
// 刷新页面数据以获取最新评论
currentPage.value = 1;
hasMore.value = true;
uni.$trackRecord({ uni.$trackRecord({
eventName: 'comment', eventName: 'comment',
eventType: 'comment', eventType: 'comment',
@@ -504,203 +354,48 @@ const submitComment = async ({ content, parentCommentId, replyToCommentId, succe
elementContent: `评论项_${detailData.value.name}`, elementContent: `评论项_${detailData.value.name}`,
customParams: { customParams: {
comment: content, comment: content,
replyToCommentId: replyToCommentId || '', replyToCommentId: replyTarget?.replyToCommentId || '',
page: 'rating_detail' page: 'rating_detail'
} }
}); });
return true; };
const handleSendComment = async (payload) => {
if (!isLoggedIn.value) {
openLoginPopup();
return;
}
if (!detailData.value.topicId || !itemId.value || isSendingComment.value) return;
try {
isSendingComment.value = true;
uni.showLoading({ title: '发送中...' });
await publishTopicComment({
content: payload.content,
mode: 'comment',
replyTarget: null
});
uni.hideLoading();
handleCommentPublished({
mode: 'comment',
content: payload.content,
replyTarget: null
});
attitudePanelRef.value?.resetComment?.();
await commentSectionRef.value?.refreshComments?.();
} catch (error) { } catch (error) {
uni.hideLoading(); uni.hideLoading();
uni.showToast({ uni.showToast({
title: '发送失败', title: '发送失败',
icon: 'none' icon: 'none'
}); });
return false;
} finally { } finally {
isSendingComment.value = false; isSendingComment.value = false;
isSendingReply.value = false;
} }
}; };
const handleSendComment = async (payload) => {
if (isSendingComment.value) return;
const success = await submitComment({
content: payload.content,
successMode: 'comment'
});
if (!success) return;
currentPage.value = 1;
hasMore.value = true;
attitudePanelRef.value?.resetComment?.();
await getCommentsData({ replace: true });
};
const handleSendReply = async () => {
const content = replyContent.value.trim();
if (!content) {
uni.showToast({ title: '请输入回复内容', icon: 'none' });
return;
}
if (!replyTarget.value || isSendingReply.value) return;
const success = await submitComment({
content,
parentCommentId: replyTarget.value.parentCommentId,
replyToCommentId: replyTarget.value.replyToCommentId,
successMode: 'reply'
});
if (!success) return;
closeReplyPopup();
await getCommentsData({ replace: true });
};
const switchTab = (tab) => {
if (currentTab.value === tab) return;
currentTab.value = tab;
currentPage.value = 1;
hasMore.value = true;
commentError.value = '';
closeReplyPopup();
getCommentsData({ replace: true });
};
const resolveCommentHasMore = (res, list) => {
const data = res?.data || res || {};
const hasNext = data?.hasNext || res?.hasNext;
if (typeof hasNext === 'boolean') return hasNext;
const pages = Number(data?.pages || res?.pages || 0);
if (pages > 0) return currentPage.value < pages;
const total = Number(data?.total || res?.total || 0);
if (total > 0) {
const size = Number(data?.size || data?.pageSize || res?.size || res?.pageSize || list.length || 1);
return currentPage.value * size < total;
}
return list.length > 0;
};
const getCommentsData = async ({ replace = false } = {}) => {
if (!detailData.value.topicId || !itemId.value || commentLoading.value) return;
try {
commentLoading.value = true;
commentError.value = '';
const orderBy = currentTab.value;
const res = await topicItemCommentList(detailData.value.topicId, itemId.value, currentPage.value, orderBy);
const rawList =
res?.data?.records ||
res?.data?.list ||
res?.records ||
res?.list ||
(Array.isArray(res?.data) ? res.data : []);
const list = Array.isArray(rawList) ? rawList : [];
const formattedList = list.map((item) => normalizeCommentItem(item));
if (currentPage.value === 1 || replace) {
comments.value = formattedList;
} else {
comments.value = [...comments.value, ...formattedList];
}
hasMore.value = resolveCommentHasMore(res, list);
} catch (error) {
console.error('获取评论列表失败:', error);
commentError.value = '请检查网络后重试';
if (currentPage.value > 1) {
currentPage.value -= 1;
}
} finally {
commentLoading.value = false;
}
};
const retryLoadComments = () => {
if (!comments.value.length) {
currentPage.value = 1;
}
closeReplyPopup();
getCommentsData({ replace: currentPage.value === 1 });
};
const loadReplies = async (comment, page = 1) => {
if (!comment?.id) return;
patchCommentItem(comment.id, (item) => ({
...item,
repliesLoading: true
}));
try {
const res = await topicItemCommentReplyList({
rootCommentId: comment.id,
page
});
const data = res?.data || res || {};
const rawList = data?.list || res?.list || [];
const list = Array.isArray(rawList) ? rawList : [];
const normalizedReplies = list.map((reply) => normalizeCommentItem(reply, comment));
const hasMoreReplies = resolveReplyHasMore(res, list, page);
patchCommentItem(comment.id, (item) => ({
...item,
repliesLoading: false,
repliesLoaded: true,
repliesPage: page,
repliesHasMore: hasMoreReplies,
replies: page === 1 ? normalizedReplies : [...(item.replies || []), ...normalizedReplies]
}));
} catch (error) {
patchCommentItem(comment.id, (item) => ({
...item,
repliesLoading: false
}));
uni.showToast({
title: '加载回复失败',
icon: 'none'
});
}
};
const handleToggleReplies = (comment) => {
if (comment.repliesLoading || comment.repliesLoaded) return;
loadReplies(comment, 1);
};
const handleLoadMoreReplies = (comment) => {
if (comment.repliesLoading || !comment.repliesHasMore) return;
loadReplies(comment, Number(comment.repliesPage || 1) + 1);
};
const handleCommentLikeChange = ({ id, parentId, isReply, isLiked, likes }) => {
comments.value = comments.value.map((item) => {
if (!isReply && item.id !== id) return item;
if (isReply && item.id !== parentId) return item;
if (isReply) {
return {
...item,
replies: (item.replies || []).map((reply) => {
if (reply.id !== id) return reply;
return {
...reply,
isLiked,
likes
};
})
};
}
return {
...item,
isLiked,
likes
};
});
};
const getDetailData = async () => { const getDetailData = async () => {
if (!itemId.value) return; if (!itemId.value) return;
try { try {
@@ -720,21 +415,9 @@ const getDetailData = async () => {
userAction: data.userAction || "" userAction: data.userAction || ""
}; };
// 如果接口返回了当前用户的态度,初始化它 currentAction.value = data.userAction || '';
if (data.userAction) {
currentAction.value = data.userAction;
}
// 如果有评论数据,更新评论 (兼容老接口一并返回的情况,但推荐通过 getCommentsData 单独获取) await commentSectionRef.value?.refreshComments?.();
if (data.comments && Array.isArray(data.comments) && currentPage.value === 1) {
// 如果后端在详情里依然返回了一部分评论
// comments.value = data.comments;
}
// 拉取真实的评论列表
if (currentPage.value === 1) {
getCommentsData({ replace: true });
}
getPkPreviewData(); getPkPreviewData();
} catch (error) { } catch (error) {
console.error('获取详情失败:', error); console.error('获取详情失败:', error);
@@ -749,12 +432,6 @@ const getDetailData = async () => {
}; };
onLoad((options) => { onLoad((options) => {
if (uni.onKeyboardHeightChange) {
keyboardHeightListener = (res) => {
replyKeyboardHeight.value = res?.height || 0;
};
uni.onKeyboardHeightChange(keyboardHeightListener);
}
uni.$trackRecord({ uni.$trackRecord({
eventName: "rating_item_detail_page_visit", eventName: "rating_item_detail_page_visit",
eventType: `visit`, eventType: `visit`,
@@ -770,11 +447,6 @@ onLoad((options) => {
}); });
const handleLoginSuccess = () => { const handleLoginSuccess = () => {
currentPage.value = 1;
hasMore.value = true;
comments.value = [];
commentError.value = '';
closeReplyPopup();
getDetailData(); getDetailData();
}; };
@@ -800,24 +472,11 @@ onShareTimeline(async () => {
}); });
onPullDownRefresh(() => { onPullDownRefresh(() => {
currentPage.value = 1;
hasMore.value = true;
comments.value = [];
commentError.value = '';
closeReplyPopup();
getDetailData(); getDetailData();
}); });
onUnload(() => {
if (uni.offKeyboardHeightChange && keyboardHeightListener) {
uni.offKeyboardHeightChange(keyboardHeightListener);
}
});
onReachBottom(() => { onReachBottom(() => {
if (!hasMore.value || commentLoading.value) return; commentSectionRef.value?.loadMoreComments?.();
currentPage.value += 1;
getCommentsData();
}); });
</script> </script>
@@ -1101,258 +760,4 @@ onReachBottom(() => {
.blue-text { color: #4d44f1; } .blue-text { color: #4d44f1; }
.yellow-text { color: #333; } .yellow-text { color: #333; }
/* 评论区 */
.comments-section {
padding: 32rpx;
}
.tabs-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 32rpx;
}
.tabs {
display: flex;
gap: 40rpx;
}
.tab {
font-size: 32rpx;
color: #999;
font-weight: 500;
position: relative;
padding-bottom: 12rpx;
transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
font-family: -apple-system, BlinkMacSystemFont, 'Helvetica Neue', Helvetica, Segoe UI, Arial, Roboto, 'PingFang SC', 'miui', 'Hiragino Sans GB', 'Microsoft Yahei', sans-serif;
}
.tab.active {
color: #111;
font-size: 36rpx;
font-weight: 700; /* 稍微减轻字重从800改为700显得不那么生硬 */
}
.tab.active::after {
content: '';
position: absolute;
bottom: 0;
left: 50%;
transform: translateX(-50%);
width: 32rpx;
height: 8rpx;
background: linear-gradient(90deg, #4d44f1, #8a78ff);
border-radius: 4rpx;
}
.filter-icon {
width: 40rpx;
height: 40rpx;
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='%23666' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cline x1='4' y1='21' x2='4' y2='14'%3E%3C/line%3E%3Cline x1='4' y1='10' x2='4' y2='3'%3E%3C/line%3E%3Cline x1='12' y1='21' x2='12' y2='12'%3E%3C/line%3E%3Cline x1='12' y1='8' x2='12' y2='3'%3E%3C/line%3E%3Cline x1='20' y1='21' x2='20' y2='16'%3E%3C/line%3E%3Cline x1='20' y1='12' x2='20' y2='3'%3E%3C/line%3E%3Cline x1='1' y1='14' x2='7' y2='14'%3E%3C/line%3E%3Cline x1='9' y1='8' x2='15' y2='8'%3E%3C/line%3E%3Cline x1='17' y1='16' x2='23' y2='16'%3E%3C/line%3E%3C/svg%3E");
background-size: cover;
transition: opacity 0.2s;
}
.filter-icon:active {
opacity: 0.7;
}
.comment-list {
display: flex;
flex-direction: column;
min-height: 400rpx;
}
.comment-state {
min-height: 400rpx;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
text-align: center;
color: #999;
padding: 56rpx 40rpx;
box-sizing: border-box;
background: linear-gradient(180deg, rgba(247, 248, 255, 0.92) 0%, rgba(255, 255, 255, 0.98) 100%);
border-radius: 28rpx;
border: 2rpx solid #f1f2fb;
}
.comment-empty-visual {
position: relative;
width: 180rpx;
height: 180rpx;
display: flex;
align-items: center;
justify-content: center;
margin-bottom: 28rpx;
}
.comment-empty-orbit {
position: absolute;
border-radius: 50%;
border: 2rpx solid rgba(123, 70, 241, 0.12);
}
.orbit-1 {
width: 180rpx;
height: 180rpx;
}
.orbit-2 {
width: 132rpx;
height: 132rpx;
border-color: rgba(77, 68, 241, 0.18);
}
.comment-empty-core {
width: 96rpx;
height: 96rpx;
border-radius: 32rpx;
background: linear-gradient(135deg, #7668ff, #4d44f1);
box-shadow: 0 18rpx 36rpx rgba(94, 83, 255, 0.2);
display: flex;
align-items: center;
justify-content: center;
}
.comment-empty-emoji {
font-size: 44rpx;
}
.comment-state-title {
font-size: 32rpx;
color: #1f2430;
font-weight: 700;
margin-bottom: 14rpx;
letter-spacing: 0.5rpx;
}
.comment-state-desc {
font-size: 25rpx;
color: #70778a;
line-height: 1.7;
}
.comment-state-tip {
margin-top: 14rpx;
font-size: 22rpx;
color: #a7adbc;
line-height: 1.6;
}
.comment-state-btn {
margin-top: 24rpx;
height: 72rpx;
line-height: 72rpx;
padding: 0 32rpx;
border-radius: 999rpx;
background: #4d44f1;
color: #fff;
font-size: 26rpx;
}
.comment-state-btn::after {
border: none;
}
.load-more {
text-align: center;
padding: 40rpx 0 0;
color: #999;
font-size: 24rpx;
}
.reply-popup-mask {
position: fixed;
inset: 0;
background: rgba(15, 23, 42, 0.24);
z-index: 998;
}
.reply-popup {
position: fixed;
left: 0;
right: 0;
bottom: 0;
z-index: 999;
padding: 24rpx 24rpx calc(env(safe-area-inset-bottom) + 24rpx);
background: #ffffff;
border-radius: 28rpx 28rpx 0 0;
box-shadow: 0 -12rpx 36rpx rgba(15, 23, 42, 0.12);
}
.reply-popup-header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 20rpx;
margin-bottom: 20rpx;
}
.reply-popup-user {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 10rpx;
}
.reply-popup-label {
font-size: 24rpx;
color: #6b7280;
}
.reply-popup-name {
font-size: 26rpx;
font-weight: 700;
color: #111827;
}
.reply-popup-close {
font-size: 24rpx;
color: #8b8f98;
}
.reply-popup-input-wrap {
display: flex;
align-items: center;
gap: 16rpx;
}
.reply-popup-input {
flex: 1;
height: 84rpx;
padding: 0 28rpx;
border-radius: 24rpx;
background: #f4f6fb;
font-size: 28rpx;
color: #1f2937;
box-sizing: border-box;
}
.reply-popup-placeholder {
color: #9ca3af;
}
.reply-popup-send {
min-width: 132rpx;
height: 84rpx;
line-height: 84rpx;
margin: 0;
padding: 0 24rpx;
border-radius: 24rpx;
background: linear-gradient(135deg, #111827 0%, #374151 100%);
color: #ffffff;
font-size: 26rpx;
font-weight: 700;
}
.reply-popup-send.disabled {
opacity: 0.45;
}
.reply-popup-send::after {
border: none;
}
</style> </style>