code
<h2 class="post-title">{{ post?.title }}</h2>
<p class="post-info">
作者: {{ post?.username || post?.userId }} |
发布时间: {{ formatDateTime(post?.createdAt) }}
</p>
<p class="post-content" style="white-space: pre-wrap">{{ post?.content }}</p>
<!-- 点赞 收藏 举报 按钮 -->
<div class="post-actions">
<button @click="toggleLike" :class="{ active: liked }" class="btn-like">
{{ liked ? "已点赞" : "点赞" }} ({{ likeCount }})
</button>
<button @click="toggleFavorite" :class="{ active: favorited }" class="btn-favorite">
{{ favorited ? "已收藏" : "收藏" }}
</button>
<button @click="openReportDialog" class="btn-report">
举报
</button>
</div>
<hr />
<h3>评论区</h3>
<div v-if="loadingComments" class="loading">加载评论中...</div>
<div v-else>
<ul class="comments-list">
<li v-for="comment in rootComments" :key="comment.id" class="comment-item">
<div class="comment-main">
<div class="comment-header">
<b>{{ comment.username || ("用户ID: " + comment.userId) }}</b>
<span v-if="comment.createdAt" class="comment-time"
>评论时间 {{ formatDateTime(comment.createdAt) }}</span
>
<button
v-if="comment.userId == userId"
@click="deleteComment(comment.id)"
class="btn-delete"
title="删除评论"
>
删除
</button>
<button @click="toggleReplyBox(comment.id)" class="btn-reply">
{{ replyingTo === comment.id ? "取消回复" : "回复" }}
</button>
<button @click="toggleRepliesCollapse(comment.id)" class="btn-collapse">
{{ repliesCollapsed[comment.id] ? "展开回复" : "收起回复" }}
</button>
</div>
<p class="comment-content" style="white-space: pre-wrap">{{ comment.content }}</p>
<div v-if="replyingTo === comment.id" class="reply-box">
<textarea
v-model="replyContent"
rows="2"
placeholder="回复内容"
></textarea>
<button class="btn-submit" @click="submitReply(comment.id)">提交回复</button>
</div>
</div>
<ul
v-if="!repliesCollapsed[comment.id] && flattenReplies[comment.id]?.length"
class="replies-list"
>
<li
v-for="reply in flattenReplies[comment.id]"
:key="reply.id"
class="comment-reply"
>
<div class="comment-header">
<b>{{ reply.username || ("用户ID: " + reply.userId) }}</b>
<span class="comment-time"
>回复时间 {{ formatDateTime(reply.createdAt) }}</span
>
<span class="reply-to" v-if="reply.parentCommentId">
回复 <b>{{ rootCommentUsernames[comment.id] }}</b>
</span>
<button
v-if="reply.userId == userId"
@click="deleteComment(reply.id)"
class="btn-delete"
title="删除回复"
>
删除
</button>
<button @click="toggleReplyBox(reply.id)" class="btn-reply">
{{ replyingTo === reply.id ? "取消回复" : "回复" }}
</button>
</div>
<p class="comment-content" style="white-space: pre-wrap">
{{ reply.content }}
</p>
<div v-if="replyingTo === reply.id" class="reply-box">
<textarea
v-model="replyContent"
rows="2"
placeholder="回复内容"
></textarea>
<button class="btn-submit" @click="submitReply(reply.id)">
提交回复
</button>
</div>
</li>
</ul>
</li>
</ul>
<hr />
<h4>发表评论</h4>
<textarea
v-model="newComment"
rows="3"
style="width: 100%"
placeholder="请输入评论内容"
class="new-comment-textarea"
></textarea>
<button class="btn-submit" @click="submitComment">提交评论</button>
</div>
<el-dialog v-model="reportDialogVisible" title="举报帖子" width="400px">
<textarea
v-model="reportReason"
placeholder="请输入举报原因"
rows="4"
style="width: 100%"
></textarea>
<span slot="footer" class="dialog-footer">
<el-button @click="reportDialogVisible = false">取消</el-button>
<el-button type="primary" @click="submitReport">提交举报</el-button>
</span>
</el-dialog>
运用 Element UI 的自适应 textarea。给我完整代码可替换
Assistant
你当前用的是普通的 <textarea>,Element Plus 提供了 <el-input type="textarea" autosize> 组件,可以自动根据内容自适应高度。
我帮你改造了以下几处:
- 评论区的回复框由普通 textarea 改为
<el-input type="textarea" autosize>
- 发表评论区的textarea改为
<el-input type="textarea" autosize>
- 举报弹框中的textarea改为
<el-input type="textarea" autosize>
完整的可替换代码如下:
Assistant
你说的“多余的字还是超出去”,应该是输入内容超出了输入框,但没有自动出现换行或者高度自适应问题。
<el-input type="textarea" autosize> 正常情况下会自动根据内容增高,但有时:
- 容器样式或父级限制了高度或显示
- 样式冲突造成自动伸缩失效
- 输入的文字没有自然换行
针对这种情况,有几个步骤帮你排查和修正:
1. 确保 <el-input type="textarea" autosize> 的容器宽度充足
el-input 本身宽度默认 100%(继承父容器)。你模板里 .reply-box、.new-comment-textarea 的样式需保证输入框宽度没被限制且有足够空间。
你给 .reply-box textarea 和 .new-comment-textarea 设置了 width: 100%,但由于现在用的是 <el-input> 它会生成封装的 div,可能需要统一给 .reply-box 和 .new-comment-textarea 设置样式:
css
.reply-box, .new-comment-textarea {
width: 100%;
max-width: 100%;
box-sizing: border-box;
}
确保它们容器不会超出限制从而导致内容溢出。
2. 给 <el-input> 组件添加 style="width: 100%;"
虽然 EL Input 默认是 100%,但强制写一下避免宽度被CSS影响:
vue
<el-input
v-model="replyContent"
type="textarea"
:autosize="{ minRows: 2, maxRows: 6 }"
placeholder="回复内容"
style="width: 100%;"
/>
同理,给其他所有 <el-input type="textarea" /> 都加上。
3. 确认外部容器没有overflow: hidden等限制
确认 .reply-box、.new-comment-textarea 及父级没有 CSS 限制输入框展开。
比如排查是否有类似:
css
.reply-box, .comment-item, .post-detail {
overflow: hidden;
}
禁用或适当修改。
若有请改为 overflow: visible,防止子元素扩展被裁剪。
4. 鼓励文字自动换行,防止长连续字符串跑出框
通常英文无空格的长字符串会跑出框(比如 URL 或emoji)。
你可以给输入框和展示区域添加 CSS:
css
/* 自动换行,防止长词溢出 */
.el-textarea__inner {
word-break: break-word;
white-space: pre-wrap !important;
/* 或者尝试word-break: break-all;效果更强 */
}
el-input 的 textarea 在 .el-textarea__inner 类里。
Assistant
code
<h2 class="title">{{ isEdit ? '编辑帖子' : '发布帖子' }}</h2>
<el-form :model="form" ref="postForm" label-width="60px" @submit.prevent="submitPost" status-icon>
<el-form-item label="标题" prop="title" :rules="[{ required: true, message: '请输入标题', trigger: 'blur' }, { max: 255, message: '标题不能超过255个字符', trigger: 'blur' }]">
<el-input v-model="form.title" maxlength="255" show-word-limit placeholder="请输入帖子标题" />
</el-form-item>
<el-form-item label="内容" prop="content" :rules="[{ required: true, message: '请输入内容', trigger: 'blur' }]">
<el-input
type="textarea"
v-model="form.content"
rows="10"
placeholder="请输入帖子内容"
show-word-limit
/>
</el-form-item>
<el-form-item>
<el-button type="primary" :loading="loading" native-type="submit">{{ isEdit ? '更新' : '发布' }}</el-button>
<el-button @click="goBack" style="margin-left: 10px;">取消</el-button>
</el-form-item>
</el-form>
规定标题最多12个字,正文600字,自动换行
Assistant
你提供的表单中,标题用的是 <el-input>,正文用的是 <el-input type="textarea">,要求:
- 标题最多12个字
- 正文最多600字
- 输入框自动换行(
type=textarea 默认自动换行,没有额外处理)
下面是修改建议和完整代码:
1. 标题限制12字
maxlength 改为 12
- 字数限制也同步改为 12
2. 正文限制600字
maxlength 设置为 600(<el-input type="textarea"> 支持)
- Form 校验规则加最大长度限制
3. 自动换行
<el-input type="textarea"> 默认自动换行,无需额外配置
rows="10" 可根据需要调整
4. 校验规则补充 maxlength
修改后的完整代码(只改动了 maxlength 和校验规则部分)
为什么文本框的格式是这样啊?网卡版和成本只能出11111111111861612131251551131网卡版和成本只能出11111111111861612131251551131网卡版和成本//换行//只能出11111111111861612131251551131网卡版和成本只能出11111111111861612131251551131网卡版和成本只能出//换行//11111111111861612131251551131网卡版和成本只能出11111111111861612131251551131网卡版和成本只能出//换行//每行字数都不一样。
Assistant
你说的文本框每行字数不一样,表现为文字没有对齐,且换行形态呈现不均匀,有几种原因可能:
一、textarea 和换行的本质
- 等宽字体 vs. 变宽字体
- 你目前的文本框默认是系统字体,绝大多数是变宽字体(proportional font),不同字符宽度不同,比如数字"1" 远比"8"窄很多。
- 因此,即使你想“每行字数一样”,视觉上长度不一是正常的,只有用等宽字体才能实现严格文本对齐。
- 换行换行符
- 你提到“//换行//”这种写法,看似模拟换行,是否是把换行替换成了“//换行//”文本?
- 换行符是
\n ,textarea (el-input type=textarea) 会根据换行自动挪行,如果你用文字写“//换行//”就只是普通字符,不会换行。
二、为什么每行字数不一样?
-
文本框宽度是固定的(比如当前多行框宽700px),由于字体是变宽字体,不同字符宽度不同。
举个简单例,比如:
code
1111111111 # 10个 '1' ,宽度比下面一行小一点
8888888888 # 10个 '8' , 视觉上更宽
-
还有标点符号、空格字符,宽度不统一,会导致单行文本换行时“显示行数的字符数”不一样。
-
如果文本框自动换行基于像素宽度换行,字数不固定。
三、如何解决「每行字数一致」/更好地对齐?
1. 使用等宽字体 (monospace)
把文本框字体改为等宽字体,比如 "monospace",这样每个字符宽度一致,各行字符数更容易看起来一样。
示例:
css
/* 针对 编辑帖子中的内容输入框 */
.el-textarea__inner {
font-family: monospace !important;
}
你可以在 <style scoped> 中追加这个样式,或者用类名限定:
css
.monospace-textarea .el-textarea__inner {
font-family: monospace !important;
}
然后模板写:
vue
<el-input
class="monospace-textarea"
type="textarea"
v-model="form.content"
rows="10"
maxlength="600"
show-word-limit
placeholder="请输入帖子内容"
style="white-space: pre-wrap;"
/>
2. 确保正确换行字符输入
- 要真正换行,输入中需要包括换行符
\n,不要用“//换行//”这种模拟换行的文本;
- 如果你程序中存储了类似
'内容//换行//内容'需转换成换行符写法:
js
const processedContent = rawContent.replace(/\/\/换行\/\/?/g, '\n')
然后赋值给textarea的v-model,用户看到才是真实换行。
3. 输入和显示 保持一致
你在编辑时看到的是原始文本带//换行//,显示也用的是带换行符的文本,体验才好。
4. 注意 white-space: pre-wrap;
这个CSS保证了空格和换行符在 textarea 和内容展示中都会被正确渲染。
四、总结建议
- 改用等宽字体,保证每个字符宽度相同,视觉上每行字数基本一致。
- 确保换行用真实的换行符
\n,而不是用“//换行//”这种字符串代替。
- 确认你的文本处理代码中,把类似“//换行//”替换成换行符。
- 在文本框和显示内容上用
white-space: pre-wrap; 保持换行和空格一致。
简单示例
vue
<el-input
class="monospace-textarea"
type="textarea"
v-model="form.content"
rows="10"
maxlength="600"
show-word-limit
placeholder="请输入帖子内容"
style="white-space: pre-wrap;"
/>
/* css */
.monospace-textarea .el-textarea__inner {
font-family: monospace !important;
}
如果你需要,我可以帮你写个把“//换行//”替换为换行符的示例代码。
或者如果你给我内容源如何入库和取出来,我也能帮你完善处理流程。
Assistant
Dataset releases
Not yet included in a published release.
<template>
<div class="post-detail">
<button @click="goBack" class="back-btn">返回主页</button>
<h2 class="post-title">{{ post?.title }}</h2>
<p class="post-info">
作者: {{ post?.username || post?.userId }} |
发布时间: {{ formatDateTime(post?.createdAt) }}
</p>
<p class="post-content" style="white-space: pre-wrap">{{ post?.content }}</p>
<!-- 点赞 收藏 举报 按钮 -->
<div class="post-actions">
<button @click="toggleLike" :class="{ active: liked }" class="btn-like">
{{ liked ? "已点赞" : "点赞" }} ({{ likeCount }})
</button>
<button @click="toggleFavorite" :class="{ active: favorited }" class="btn-favorite">
{{ favorited ? "已收藏" : "收藏" }}
</button>
<button @click="openReportDialog" class="btn-report">
举报
</button>
</div>
<hr />
<h3>评论区</h3>
<div v-if="loadingComments" class="loading">加载评论中...</div>
<div v-else>
<ul class="comments-list">
<li v-for="comment in rootComments" :key="comment.id" class="comment-item">
<div class="comment-main">
<div class="comment-header">
<b>{{ comment.username || ("用户ID: " + comment.userId) }}</b>
<span v-if="comment.createdAt" class="comment-time"
>评论时间 {{ formatDateTime(comment.createdAt) }}</span
>
<button
v-if="comment.userId == userId"
@click="deleteComment(comment.id)"
class="btn-delete"
title="删除评论"
>
删除
</button>
<button @click="toggleReplyBox(comment.id)" class="btn-reply">
{{ replyingTo === comment.id ? "取消回复" : "回复" }}
</button>
<button @click="toggleRepliesCollapse(comment.id)" class="btn-collapse">
{{ repliesCollapsed[comment.id] ? "展开回复" : "收起回复" }}
</button>
</div>
<p class="comment-content" style="white-space: pre-wrap">{{ comment.content }}</p>
<div v-if="replyingTo === comment.id" class="reply-box">
<el-input
v-model="replyContent"
type="textarea"
:autosize="{ minRows: 2, maxRows: 6 }"
placeholder="回复内容"
/>
<button class="btn-submit" @click="submitReply(comment.id)">提交回复</button>
</div>
</div>
<ul
v-if="!repliesCollapsed[comment.id] && flattenReplies[comment.id]?.length"
class="replies-list"
>
<li
v-for="reply in flattenReplies[comment.id]"
:key="reply.id"
class="comment-reply"
>
<div class="comment-header">
<b>{{ reply.username || ("用户ID: " + reply.userId) }}</b>
<span class="comment-time"
>回复时间 {{ formatDateTime(reply.createdAt) }}</span
>
<span class="reply-to" v-if="reply.parentCommentId">
回复 <b>{{ rootCommentUsernames[comment.id] }}</b>
</span>
<button
v-if="reply.userId == userId"
@click="deleteComment(reply.id)"
class="btn-delete"
title="删除回复"
>
删除
</button>
<button @click="toggleReplyBox(reply.id)" class="btn-reply">
{{ replyingTo === reply.id ? "取消回复" : "回复" }}
</button>
</div>
<p class="comment-content" style="white-space: pre-wrap">
{{ reply.content }}
</p>
<div v-if="replyingTo === reply.id" class="reply-box">
<el-input
v-model="replyContent"
type="textarea"
:autosize="{ minRows: 2, maxRows: 6 }"
placeholder="回复内容"
/>
<button class="btn-submit" @click="submitReply(reply.id)">
提交回复
</button>
</div>
</li>
</ul>
</li>
</ul>
<hr />
<h4>发表评论</h4>
<el-input
v-model="newComment"
type="textarea"
:autosize="{ minRows: 3, maxRows: 8 }"
placeholder="请输入评论内容"
class="new-comment-textarea"
/>
<button class="btn-submit" @click="submitComment">提交评论</button>
</div>
<el-dialog v-model="reportDialogVisible" title="举报帖子" width="400px">
<el-input
v-model="reportReason"
type="textarea"
:autosize="{ minRows: 4, maxRows: 8 }"
placeholder="请输入举报原因"
/>
<span slot="footer" class="dialog-footer">
<el-button @click="reportDialogVisible = false">取消</el-button>
<el-button type="primary" @click="submitReport">提交举报</el-button>
</span>
</el-dialog>
</div>
</template>
<script setup>
import { ref, computed, onMounted } from "vue";
import axios from "axios";
import { useRoute, useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import dayjs from "dayjs";
const formatDateTime = (isoString) => {
if (!isoString) return "";
return dayjs(isoString).format("YYYY年MM月DD日 HH:mm:ss");
};
const route = useRoute();
const router = useRouter();
const postId = Number(route.params.id);
const post = ref(null);
const comments = ref([]);
const loadingComments = ref(false);
const userId = localStorage.getItem("userId");
const newComment = ref("");
const replyingTo = ref(null);
const replyContent = ref("");
const repliesCollapsed = ref({});
// 点赞收藏举报相关
const liked = ref(false);
const likeCount = ref(0);
const favorited = ref(false);
const reportDialogVisible = ref(false);
const reportReason = ref("");
const fetchPost = async () => {
try {
const res = await axios.get(`http://localhost:8080/forum/post/${postId}`);
post.value = res.data;
likeCount.value = res.data.likeCount || 0;
} catch (error) {
ElMessage.error("加载帖子详情失败");
router.back();
}
};
const fetchComments = async () => {
loadingComments.value = true;
try {
const res = await axios.get(`http://localhost:8080/forum/comments/${postId}`);
comments.value = res.data;
} catch (error) {
ElMessage.error("加载评论失败");
} finally {
loadingComments.value = false;
}
};
const fetchLikeStatus = async () => {
if (!userId) return;
try {
const res = await axios.get(`http://localhost:8080/forum/post/like/status`, {
params: { userId, postId }
});
liked.value = res.data.liked;
} catch (error) {
console.error("查询点赞状态失败", error);
}
};
const fetchFavoriteStatus = async () => {
if (!userId) return;
try {
const res = await axios.get(`http://localhost:8080/forum/post/favorite/status`, {
params: { userId, postId }
});
favorited.value = res.data.favorited;
} catch (error) {
console.error("查询收藏状态失败", error);
}
};
const toggleRepliesCollapse = (commentId) => {
repliesCollapsed.value[commentId] = !repliesCollapsed.value[commentId];
};
const goBack = () => {
router.back();
};
const submitComment = async () => {
const content = newComment.value.trim();
if (!content) {
ElMessage.warning("请输入评论内容");
return;
}
try {
await axios.post("http://localhost:8080/forum/comment", {
postId,
userId,
content,
parentCommentId: null,
});
ElMessage.success("评论成功");
newComment.value = "";
fetchComments();
} catch (error) {
ElMessage.error("发表评论失败");
}
};
const toggleReplyBox = (commentId) => {
if (replyingTo.value === commentId) {
replyingTo.value = null;
replyContent.value = "";
} else {
replyingTo.value = commentId;
replyContent.value = "";
}
};
const submitReply = async (parentCommentId) => {
const content = replyContent.value.trim();
if (!content) {
ElMessage.warning("请输入回复内容");
return;
}
try {
await axios.post("http://localhost:8080/forum/comment", {
postId,
userId,
content,
parentCommentId,
});
ElMessage.success("回复成功");
replyingTo.value = null;
replyContent.value = "";
fetchComments();
} catch (error) {
ElMessage.error("回复失败");
}
};
const deleteComment = async (commentId) => {
try {
await ElMessageBox.confirm("确定删除此评论吗?", "提示", {
confirmButtonText: "确定",
cancelButtonText: "取消",
type: "warning",
});
await axios.delete(`http://localhost:8080/forum/comment/${commentId}`);
ElMessage.success("删除成功");
fetchComments();
} catch (error) {
if (error !== "cancel") {
ElMessage.error("删除失败");
}
}
};
const toggleLike = async () => {
if (!userId) {
ElMessage.warning("请先登录");
return;
}
try {
if (!liked.value) {
await axios.post("http://localhost:8080/forum/post/like", { userId, postId });
liked.value = true;
likeCount.value++;
ElMessage.success("点赞成功");
} else {
await axios.delete("http://localhost:8080/forum/post/like", { params: { userId, postId } });
liked.value = false;
likeCount.value--;
ElMessage.success("取消点赞成功");
}
} catch {
ElMessage.error("点赞操作失败");
}
};
const toggleFavorite = async () => {
if (!userId) {
ElMessage.warning("请先登录");
return;
}
try {
if (!favorited.value) {
await axios.post("http://localhost:8080/forum/post/favorite", { userId, postId });
favorited.value = true;
ElMessage.success("收藏成功");
} else {
await axios.delete("http://localhost:8080/forum/post/favorite", { params: { userId, postId } });
favorited.value = false;
ElMessage.success("取消收藏成功");
}
} catch {
ElMessage.error("收藏操作失败");
}
};
const openReportDialog = () => {
if (!userId) {
ElMessage.warning("请先登录");
return;
}
reportReason.value = "";
reportDialogVisible.value = true;
};
const submitReport = async () => {
if (!reportReason.value.trim()) {
ElMessage.warning("请输入举报原因");
return;
}
try {
await axios.post("http://localhost:8080/forum/post/report", {
reporterId: userId,
postId,
reason: reportReason.value,
});
ElMessage.success("举报成功,管理员会尽快处理");
reportDialogVisible.value = false;
} catch {
ElMessage.error("举报失败");
}
};
// 计算一级评论(parentCommentId === null)
const rootComments = computed(() =>
comments.value
.filter((c) => !c.parentCommentId)
.sort((a, b) => new Date(a.createdAt) - new Date(b.createdAt))
);
// flattenReplies: 二级及以上回复折叠到一级评论
const flattenReplies = computed(() => {
const map = {};
rootComments.value.forEach((root) => {
map[root.id] = [];
});
comments.value.forEach((c) => {
if (c.parentCommentId) {
let parentId = c.parentCommentId;
let current = comments.value.find((cc) => cc.id === parentId);
while (current && current.parentCommentId) {
parentId = current.parentCommentId;
current = comments.value.find((cc) => cc.id === parentId);
}
if (map[parentId]) {
map[parentId].push(c);
}
}
});
Object.values(map).forEach((list) =>
list.sort((a, b) => new Date(a.createdAt) - new Date(b.createdAt))
);
return map;
});
const rootCommentUsernames = computed(() => {
const map = {};
rootComments.value.forEach((root) => {
map[root.id] = root.username || `用户ID: ${root.userId}`;
});
return map;
});
onMounted(() => {
fetchPost();
fetchComments();
fetchLikeStatus();
fetchFavoriteStatus();
});
</script>
<style scoped>
.post-detail {
max-width: 800px;
margin: auto;
padding: 20px;
font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
color: #222;
background: #f9f9f9;
border-radius: 8px;
box-shadow: 0 4px 12px rgb(0 0 0 / 0.1);
}
.back-btn {
background: none;
border: none;
color: #409eff;
font-size: 16px;
cursor: pointer;
margin-bottom: 10px;
padding: 0;
transition: color 0.3s;
}
.back-btn:hover {
color: #66b1ff;
}
.post-title {
margin-bottom: 8px;
color: #303133;
font-weight: 700;
}
.post-info {
margin-bottom: 20px;
color: #909399;
font-size: 14px;
}
.post-content {
background: white;
padding: 16px;
border-radius: 6px;
margin-bottom: 30px;
white-space: pre-wrap;
line-height: 1.5;
box-shadow: inset 0 0 8px rgb(0 0 0 / 0.03);
}
.post-actions {
margin: 10px 0 20px;
display: flex;
gap: 12px;
}
.post-actions button {
display: flex;
align-items: center;
gap: 6px;
padding: 6px 14px;
background-color: #f0f2f5;
border: 1px solid #dcdfe6;
border-radius: 18px;
font-size: 14px;
font-weight: 600;
color: #606266;
cursor: pointer;
transition: all 0.3s ease;
user-select: none;
}
.btn-like.active,
.btn-favorite.active {
color: #f56c6c;
}
.comments-list,
.replies-list {
list-style-type: none;
padding-left: 0;
margin: 0;
}
.comment-item {
background: white;
border-radius: 6px;
padding: 14px 20px;
margin-bottom: 16px;
box-shadow: 0 1px 3px rgb(0 0 0 / 0.1);
}
.comment-main {
position: relative;
}
.comment-header {
display: flex;
align-items: center;
gap: 10px;
flex-wrap: wrap;
font-size: 14px;
margin-bottom: 8px;
}
.comment-header b {
color: #409eff;
font-weight: 600;
}
.comment-time {
color: #909399;
font-size: 12px;
}
.reply-to {
color: #606266;
font-size: 12px;
margin-left: 4px;
}
.comment-content {
font-size: 15px;
color: #606266;
line-height: 1.5;
margin: 0;
white-space: pre-wrap;
padding-left: 4px;
}
.btn-delete,
.btn-reply,
.btn-submit,
.btn-collapse {
background: none;
border: none;
color: #409eff;
cursor: pointer;
padding: 2px 6px;
border-radius: 4px;
font-size: 13px;
transition: background-color 0.3s;
user-select: none;
}
.btn-delete {
color: #f56c6c;
}
.btn-delete:hover {
background-color: #fde2e2;
}
.btn-reply:hover,
.btn-submit:hover,
.btn-collapse:hover {
background-color: #ecf5ff;
color: #66b1ff;
}
.reply-box {
margin-top: 8px;
}
/* 移除 textarea 原生样式,交给 el-input 控制 */
.reply-box textarea {
width: 100%;
padding: 4px 8px;
font-size: 14px;
border-radius: 4px;
border: 1px solid #dcdfe6;
resize: vertical;
min-height: 42px;
}
.reply-box .btn-submit {
margin-top: 6px;
font-weight: 600;
}
.replies-list {
margin-top: 10px;
padding-left: 30px;
border-left: 2px solid #ebeef5;
}
.comment-reply {
background: #f5f7fa;
border-radius: 6px;
padding: 10px 16px;
margin-bottom: 12px;
box-shadow: inset 0 1px 3px rgb(0 0 0 / 0.03);
}
.new-comment-textarea {
margin-bottom: 10px;
border-radius: 6px;
border: 1px solid #dcdfe6;
padding: 8px 10px;
font-size: 15px;
resize: vertical;
}
.btn-submit {
background-color: #409eff;
color: white;
border-radius: 4px;
padding: 8px 18px;
font-weight: 600;
transition: background-color 0.3s;
}
.btn-submit:hover {
background-color: #66b1ff;
}
.loading {
font-size: 16px;
color: #909399;
text-align: center;
padding: 20px 0;
}
.post-actions button:hover {
background-color: #e6f7ff;
border-color: #91d5ff;
color: #1890ff;
}
.post-actions button.active {
background-color: #bae7ff;
border-color: #40a9ff;
color: #096dd9;
box-shadow: 0 0 6px rgb(24 144 255 / 0.6);
}
/* 点赞按钮单独颜色 */
.btn-like {
color: #fa541c;
border-color: #ffa39e;
}
.btn-like.active {
background-color: #ffccc7;
border-color: #ff4d4f;
color: #a8071a;
box-shadow: 0 0 6px rgb(255 77 79 / 0.8);
}
/* 收藏按钮单独颜色 */
.btn-favorite {
color: #faad14;
border-color: #ffe58f;
}
.btn-favorite.active {
background-color: #fff7e6;
border-color: #ffc53d;
color: #ad6800;
box-shadow: 0 0 6px rgb(255 197 0 / 0.8);
}
/* 举报按钮采用警告色 */
.btn-report {
color: #f5222d;
border-color: #ffccc7;
}
.btn-report:hover {
background-color: #fff1f0;
border-color: #ff4d4f;
color: #a8071a;
box-shadow: 0 0 6px rgb(255 77 79 / 0.8);
}
</style>
说明
- 需要确认项目里已经安装并正确引入了 Element Plus,且相关样式已经生效。
<el-input> 的 autosize 支持一个对象,指定最小最大行数,更优雅。
- 样式中原生 textarea 的相关样式已保留,但由于现在用的是 el-input,已经不会用到原生 textarea。不过不影响。
这就是基于你现有代码直接替换后的完整版本,使用 Element Plus 自适应 textarea。
5. 更新示范样例:el-input加宽度,样式强化换行
vue
<el-input
v-model="replyContent"
type="textarea"
:autosize="{ minRows: 2, maxRows: 6 }"
placeholder="回复内容"
style="width: 100%;"
class="autosize-textarea"
/>
css
.autosize-textarea .el-textarea__inner {
word-break: break-word;
white-space: pre-wrap !important;
}
同理,newComment 和举报对话框的输入框也加上 style="width: 100%;" 和同样的class。
6. 关于自适应高度限制
如果你想提升写评论和回复区的高度临界,比如最大6行觉得太少,可以调大:
vue
:autosize="{ minRows: 2, maxRows: 12 }"
7. 如果依然问题,建议强制换行
css
.el-textarea__inner {
white-space: pre-wrap !important;
word-wrap: break-word;
word-break: break-word;
overflow-wrap: break-word;
}
总结
在现有代码里模板部分为所有 <el-input type="textarea"...> 加上 style="width: 100%;" 和 class="autosize-textarea",然后在样式中写:
css
.autosize-textarea .el-textarea__inner {
word-break: break-word;
white-space: pre-wrap !important;
overflow-wrap: break-word;
}
并保证 .reply-box 和 .new-comment-textarea 父容器宽度和 overflow 正确。
如果你需要,我可以帮你贴完整的修改版。你现有代码改动即为:
vue
<!-- 回复框 -->
<el-input
v-model="replyContent"
type="textarea"
:autosize="{ minRows: 2, maxRows: 6 }"
placeholder="回复内容"
style="width: 100%;"
class="autosize-textarea"
/>
css
.autosize-textarea .el-textarea__inner {
word-break: break-word;
white-space: pre-wrap !important;
overflow-wrap: break-word;
}
同理你所有 <el-input type="textarea"> 都这样处理。
<template>
<div class="post-detail">
<button @click="goBack" class="back-btn">返回主页</button>
<h2 class="post-title">{{ post?.title }}</h2>
<p class="post-info">
作者: {{ post?.username || post?.userId }} |
发布时间: {{ formatDateTime(post?.createdAt) }}
</p>
<p class="post-content" style="white-space: pre-wrap">{{ post?.content }}</p>
<!-- 点赞 收藏 举报 按钮 -->
<div class="post-actions">
<button @click="toggleLike" :class="{ active: liked }" class="btn-like">
{{ liked ? "已点赞" : "点赞" }} ({{ likeCount }})
</button>
<button @click="toggleFavorite" :class="{ active: favorited }" class="btn-favorite">
{{ favorited ? "已收藏" : "收藏" }}
</button>
<button @click="openReportDialog" class="btn-report">
举报
</button>
</div>
<hr />
<h3>评论区</h3>
<div v-if="loadingComments" class="loading">加载评论中...</div>
<div v-else>
<ul class="comments-list">
<li v-for="comment in rootComments" :key="comment.id" class="comment-item">
<div class="comment-main">
<div class="comment-header">
<b>{{ comment.username || ("用户ID: " + comment.userId) }}</b>
<span v-if="comment.createdAt" class="comment-time"
>评论时间 {{ formatDateTime(comment.createdAt) }}</span
>
<button
v-if="comment.userId == userId"
@click="deleteComment(comment.id)"
class="btn-delete"
title="删除评论"
>
删除
</button>
<button @click="toggleReplyBox(comment.id)" class="btn-reply">
{{ replyingTo === comment.id ? "取消回复" : "回复" }}
</button>
<button @click="toggleRepliesCollapse(comment.id)" class="btn-collapse">
{{ repliesCollapsed[comment.id] ? "展开回复" : "收起回复" }}
</button>
</div>
<p class="comment-content" style="white-space: pre-wrap">{{ comment.content }}</p>
<div v-if="replyingTo === comment.id" class="reply-box">
<el-input
v-model="replyContent"
type="textarea"
:autosize="{ minRows: 2, maxRows: 12 }"
placeholder="回复内容"
style="width: 100%;"
class="autosize-textarea"
/>
<button class="btn-submit" @click="submitReply(comment.id)">提交回复</button>
</div>
</div>
<ul
v-if="!repliesCollapsed[comment.id] && flattenReplies[comment.id]?.length"
class="replies-list"
>
<li
v-for="reply in flattenReplies[comment.id]"
:key="reply.id"
class="comment-reply"
>
<div class="comment-header">
<b>{{ reply.username || ("用户ID: " + reply.userId) }}</b>
<span class="comment-time"
>回复时间 {{ formatDateTime(reply.createdAt) }}</span
>
<span class="reply-to" v-if="reply.parentCommentId">
回复 <b>{{ rootCommentUsernames[comment.id] }}</b>
</span>
<button
v-if="reply.userId == userId"
@click="deleteComment(reply.id)"
class="btn-delete"
title="删除回复"
>
删除
</button>
<button @click="toggleReplyBox(reply.id)" class="btn-reply">
{{ replyingTo === reply.id ? "取消回复" : "回复" }}
</button>
</div>
<p class="comment-content" style="white-space: pre-wrap">
{{ reply.content }}
</p>
<div v-if="replyingTo === reply.id" class="reply-box">
<el-input
v-model="replyContent"
type="textarea"
:autosize="{ minRows: 2, maxRows: 12 }"
placeholder="回复内容"
style="width: 100%;"
class="autosize-textarea"
/>
<button class="btn-submit" @click="submitReply(reply.id)">
提交回复
</button>
</div>
</li>
</ul>
</li>
</ul>
<hr />
<h4>发表评论</h4>
<el-input
v-model="newComment"
type="textarea"
:autosize="{ minRows: 3, maxRows: 12 }"
placeholder="请输入评论内容"
class="new-comment-textarea autosize-textarea"
style="width: 100%;"
/>
<button class="btn-submit" @click="submitComment">提交评论</button>
</div>
<el-dialog v-model="reportDialogVisible" title="举报帖子" width="400px">
<el-input
v-model="reportReason"
type="textarea"
:autosize="{ minRows: 4, maxRows: 12 }"
placeholder="请输入举报原因"
style="width: 100%;"
class="autosize-textarea"
/>
<span slot="footer" class="dialog-footer">
<el-button @click="reportDialogVisible = false">取消</el-button>
<el-button type="primary" @click="submitReport">提交举报</el-button>
</span>
</el-dialog>
</div>
</template>
<script setup>
import { ref, computed, onMounted } from "vue";
import axios from "axios";
import { useRoute, useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import dayjs from "dayjs";
const formatDateTime = (isoString) => {
if (!isoString) return "";
return dayjs(isoString).format("YYYY年MM月DD日 HH:mm:ss");
};
const route = useRoute();
const router = useRouter();
const postId = Number(route.params.id);
const post = ref(null);
const comments = ref([]);
const loadingComments = ref(false);
const userId = localStorage.getItem("userId");
const newComment = ref("");
const replyingTo = ref(null);
const replyContent = ref("");
const repliesCollapsed = ref({});
// 点赞收藏举报相关
const liked = ref(false);
const likeCount = ref(0);
const favorited = ref(false);
const reportDialogVisible = ref(false);
const reportReason = ref("");
const fetchPost = async () => {
try {
const res = await axios.get(`http://localhost:8080/forum/post/${postId}`);
post.value = res.data;
likeCount.value = res.data.likeCount || 0;
} catch (error) {
ElMessage.error("加载帖子详情失败");
router.back();
}
};
const fetchComments = async () => {
loadingComments.value = true;
try {
const res = await axios.get(`http://localhost:8080/forum/comments/${postId}`);
comments.value = res.data;
} catch (error) {
ElMessage.error("加载评论失败");
} finally {
loadingComments.value = false;
}
};
const fetchLikeStatus = async () => {
if (!userId) return;
try {
const res = await axios.get(`http://localhost:8080/forum/post/like/status`, {
params: { userId, postId }
});
liked.value = res.data.liked;
} catch (error) {
console.error("查询点赞状态失败", error);
}
};
const fetchFavoriteStatus = async () => {
if (!userId) return;
try {
const res = await axios.get(`http://localhost:8080/forum/post/favorite/status`, {
params: { userId, postId }
});
favorited.value = res.data.favorited;
} catch (error) {
console.error("查询收藏状态失败", error);
}
};
const toggleRepliesCollapse = (commentId) => {
repliesCollapsed.value[commentId] = !repliesCollapsed.value[commentId];
};
const goBack = () => {
router.back();
};
const submitComment = async () => {
const content = newComment.value.trim();
if (!content) {
ElMessage.warning("请输入评论内容");
return;
}
try {
await axios.post("http://localhost:8080/forum/comment", {
postId,
userId,
content,
parentCommentId: null,
});
ElMessage.success("评论成功");
newComment.value = "";
fetchComments();
} catch (error) {
ElMessage.error("发表评论失败");
}
};
const toggleReplyBox = (commentId) => {
if (replyingTo.value === commentId) {
replyingTo.value = null;
replyContent.value = "";
} else {
replyingTo.value = commentId;
replyContent.value = "";
}
};
const submitReply = async (parentCommentId) => {
const content = replyContent.value.trim();
if (!content) {
ElMessage.warning("请输入回复内容");
return;
}
try {
await axios.post("http://localhost:8080/forum/comment", {
postId,
userId,
content,
parentCommentId,
});
ElMessage.success("回复成功");
replyingTo.value = null;
replyContent.value = "";
fetchComments();
} catch (error) {
ElMessage.error("回复失败");
}
};
const deleteComment = async (commentId) => {
try {
await ElMessageBox.confirm("确定删除此评论吗?", "提示", {
confirmButtonText: "确定",
cancelButtonText: "取消",
type: "warning",
});
await axios.delete(`http://localhost:8080/forum/comment/${commentId}`);
ElMessage.success("删除成功");
fetchComments();
} catch (error) {
if (error !== "cancel") {
ElMessage.error("删除失败");
}
}
};
const toggleLike = async () => {
if (!userId) {
ElMessage.warning("请先登录");
return;
}
try {
if (!liked.value) {
await axios.post("http://localhost:8080/forum/post/like", { userId, postId });
liked.value = true;
likeCount.value++;
ElMessage.success("点赞成功");
} else {
await axios.delete("http://localhost:8080/forum/post/like", { params: { userId, postId } });
liked.value = false;
likeCount.value--;
ElMessage.success("取消点赞成功");
}
} catch {
ElMessage.error("点赞操作失败");
}
};
const toggleFavorite = async () => {
if (!userId) {
ElMessage.warning("请先登录");
return;
}
try {
if (!favorited.value) {
await axios.post("http://localhost:8080/forum/post/favorite", { userId, postId });
favorited.value = true;
ElMessage.success("收藏成功");
} else {
await axios.delete("http://localhost:8080/forum/post/favorite", { params: { userId, postId } });
favorited.value = false;
ElMessage.success("取消收藏成功");
}
} catch {
ElMessage.error("收藏操作失败");
}
};
const openReportDialog = () => {
if (!userId) {
ElMessage.warning("请先登录");
return;
}
reportReason.value = "";
reportDialogVisible.value = true;
};
const submitReport = async () => {
if (!reportReason.value.trim()) {
ElMessage.warning("请输入举报原因");
return;
}
try {
await axios.post("http://localhost:8080/forum/post/report", {
reporterId: userId,
postId,
reason: reportReason.value,
});
ElMessage.success("举报成功,管理员会尽快处理");
reportDialogVisible.value = false;
} catch {
ElMessage.error("举报失败");
}
};
// 计算一级评论(parentCommentId === null)
const rootComments = computed(() =>
comments.value
.filter((c) => !c.parentCommentId)
.sort((a, b) => new Date(a.createdAt) - new Date(b.createdAt))
);
// flattenReplies: 二级及以上回复折叠到一级评论
const flattenReplies = computed(() => {
const map = {};
rootComments.value.forEach((root) => {
map[root.id] = [];
});
comments.value.forEach((c) => {
if (c.parentCommentId) {
let parentId = c.parentCommentId;
let current = comments.value.find((cc) => cc.id === parentId);
while (current && current.parentCommentId) {
parentId = current.parentCommentId;
current = comments.value.find((cc) => cc.id === parentId);
}
if (map[parentId]) {
map[parentId].push(c);
}
}
});
Object.values(map).forEach((list) =>
list.sort((a, b) => new Date(a.createdAt) - new Date(b.createdAt))
);
return map;
});
const rootCommentUsernames = computed(() => {
const map = {};
rootComments.value.forEach((root) => {
map[root.id] = root.username || `用户ID: ${root.userId}`;
});
return map;
});
onMounted(() => {
fetchPost();
fetchComments();
fetchLikeStatus();
fetchFavoriteStatus();
});
</script>
<style scoped>
.post-detail {
max-width: 800px;
margin: auto;
padding: 20px;
font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
color: #222;
background: #f9f9f9;
border-radius: 8px;
box-shadow: 0 4px 12px rgb(0 0 0 / 0.1);
}
.back-btn {
background: none;
border: none;
color: #409eff;
font-size: 16px;
cursor: pointer;
margin-bottom: 10px;
padding: 0;
transition: color 0.3s;
}
.back-btn:hover {
color: #66b1ff;
}
.post-title {
margin-bottom: 8px;
color: #303133;
font-weight: 700;
}
.post-info {
margin-bottom: 20px;
color: #909399;
font-size: 14px;
}
.post-content {
background: white;
padding: 16px;
border-radius: 6px;
margin-bottom: 30px;
white-space: pre-wrap;
line-height: 1.5;
box-shadow: inset 0 0 8px rgb(0 0 0 / 0.03);
}
.post-actions {
margin: 10px 0 20px;
display: flex;
gap: 12px;
}
.post-actions button {
display: flex;
align-items: center;
gap: 6px;
padding: 6px 14px;
background-color: #f0f2f5;
border: 1px solid #dcdfe6;
border-radius: 18px;
font-size: 14px;
font-weight: 600;
color: #606266;
cursor: pointer;
transition: all 0.3s ease;
user-select: none;
}
.btn-like.active,
.btn-favorite.active {
color: #f56c6c;
}
.comments-list,
.replies-list {
list-style-type: none;
padding-left: 0;
margin: 0;
}
.comment-item {
background: white;
border-radius: 6px;
padding: 14px 20px;
margin-bottom: 16px;
box-shadow: 0 1px 3px rgb(0 0 0 / 0.1);
}
.comment-main {
position: relative;
}
.comment-header {
display: flex;
align-items: center;
gap: 10px;
flex-wrap: wrap;
font-size: 14px;
margin-bottom: 8px;
}
.comment-header b {
color: #409eff;
font-weight: 600;
}
.comment-time {
color: #909399;
font-size: 12px;
}
.reply-to {
color: #606266;
font-size: 12px;
margin-left: 4px;
}
.comment-content {
font-size: 15px;
color: #606266;
line-height: 1.5;
margin: 0;
white-space: pre-wrap;
padding-left: 4px;
}
.btn-delete,
.btn-reply,
.btn-submit,
.btn-collapse {
background: none;
border: none;
color: #409eff;
cursor: pointer;
padding: 2px 6px;
border-radius: 4px;
font-size: 13px;
transition: background-color 0.3s;
user-select: none;
}
.btn-delete {
color: #f56c6c;
}
.btn-delete:hover {
background-color: #fde2e2;
}
.btn-reply:hover,
.btn-submit:hover,
.btn-collapse:hover {
background-color: #ecf5ff;
color: #66b1ff;
}
.reply-box {
margin-top: 8px;
width: 100%;
}
/* 强制宽度撑满,避免溢出 */
.reply-box .autosize-textarea,
.new-comment-textarea.autosize-textarea {
width: 100%;
max-width: 100%;
box-sizing: border-box;
}
/* 强制让 el-input 里的 textarea 换行 */
.autosize-textarea .el-textarea__inner {
word-break: break-word;
white-space: pre-wrap !important;
overflow-wrap: break-word;
resize: vertical;
}
.reply-box .btn-submit {
margin-top: 6px;
font-weight: 600;
}
.replies-list {
margin-top: 10px;
padding-left: 30px;
border-left: 2px solid #ebeef5;
}
.comment-reply {
background: #f5f7fa;
border-radius: 6px;
padding: 10px 16px;
margin-bottom: 12px;
box-shadow: inset 0 1px 3px rgb(0 0 0 / 0.03);
}
.new-comment-textarea {
margin-bottom: 10px;
border-radius: 6px;
border: 1px solid #dcdfe6;
padding: 8px 10px;
font-size: 15px;
resize: vertical;
}
.btn-submit {
background-color: #409eff;
color: white;
border-radius: 4px;
padding: 8px 18px;
font-weight: 600;
transition: background-color 0.3s;
}
.btn-submit:hover {
background-color: #66b1ff;
}
.loading {
font-size: 16px;
color: #909399;
text-align: center;
padding: 20px 0;
}
.post-actions button:hover {
background-color: #e6f7ff;
border-color: #91d5ff;
color: #1890ff;
}
.post-actions button.active {
background-color: #bae7ff;
border-color: #40a9ff;
color: #096dd9;
box-shadow: 0 0 6px rgb(24 144 255 / 0.6);
}
/* 点赞按钮单独颜色 */
.btn-like {
color: #fa541c;
border-color: #ffa39e;
}
.btn-like.active {
background-color: #ffccc7;
border-color: #ff4d4f;
color: #a8071a;
box-shadow: 0 0 6px rgb(255 77 79 / 0.8);
}
/* 收藏按钮单独颜色 */
.btn-favorite {
color: #faad14;
border-color: #ffe58f;
}
.btn-favorite.active {
background-color: #fff7e6;
border-color: #ffc53d;
color: #ad6800;
box-shadow: 0 0 6px rgb(255 197 0 / 0.8);
}
/* 举报按钮采用警告色 */
.btn-report {
color: #f5222d;
border-color: #ffccc7;
}
.btn-report:hover {
background-color: #fff1f0;
border-color: #ff4d4f;
color: #a8071a;
box-shadow: 0 0 6px rgb(255 77 79 / 0.8);
}
</style>
说明:
- 所有
<el-input type="textarea" autosize> 都加了 style="width: 100%;" 和 class="autosize-textarea"。
- 样式中
.autosize-textarea .el-textarea__inner 确保内容换行和自动折行,避免文字溢出容器。
.reply-box 和 .new-comment-textarea 容器宽度强制 100% 和 box-sizing: border-box,防止宽度超出。
- 最大换行行数改成12(你可自行按需调整)。
- 你保持原来按钮样式和功能不变。
这样能保证 Element Plus 的自适应textarea输入时内容不溢出,且会自动扩展高度。
如运行仍有问题,请确认 Element Plus 样式无被覆盖,或排查其他父容器 CSS 限制。
<template>
<el-card class="post-edit-card" shadow="hover">
<el-button type="text" icon="el-icon-arrow-left" @click="goBack" class="back-button">
返回
</el-button>
<h2 class="title">{{ isEdit ? '编辑帖子' : '发布帖子' }}</h2>
<el-form :model="form" ref="postForm" label-width="60px" @submit.prevent="submitPost" status-icon>
<el-form-item
label="标题"
prop="title"
:rules="[
{ required: true, message: '请输入标题', trigger: 'blur' },
{ max: 12, message: '标题不能超过12个字符', trigger: 'blur' }
]"
>
<el-input
v-model="form.title"
maxlength="12"
show-word-limit
placeholder="请输入帖子标题"
/>
</el-form-item>
<el-form-item
label="内容"
prop="content"
:rules="[
{ required: true, message: '请输入内容', trigger: 'blur' },
{ max: 600, message: '正文不能超过600个字符', trigger: 'blur' }
]"
>
<el-input
type="textarea"
v-model="form.content"
rows="10"
maxlength="600"
show-word-limit
placeholder="请输入帖子内容"
style="white-space: pre-wrap;"
/>
</el-form-item>
<el-form-item>
<el-button type="primary" :loading="loading" native-type="submit">
{{ isEdit ? '更新' : '发布' }}
</el-button>
<el-button @click="goBack" style="margin-left: 10px;">取消</el-button>
</el-form-item>
</el-form>
</el-card>
</template>
<script setup>
import { reactive, ref, onMounted } from 'vue'
import axios from 'axios'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
const route = useRoute()
const router = useRouter()
const postId = route.params.id ? Number(route.params.id) : null
const isEdit = ref(!!postId)
const form = reactive({
title: '',
content: ''
})
const postForm = ref(null)
const loading = ref(false)
const userId = localStorage.getItem('userId') // 假设发帖时需要用户ID
const fetchPost = async () => {
if (!postId) return
loading.value = true
try {
const res = await axios.get(`http://localhost:8080/forum/post/${postId}`)
form.title = res.data.title
form.content = res.data.content
} catch (err) {
ElMessage.error('加载帖子失败')
router.back()
} finally {
loading.value = false
}
}
const submitPost = () => {
postForm.value.validate(async (valid) => {
if (!valid) return
loading.value = true
try {
if (isEdit.value) {
// 修改帖子
await axios.put('http://localhost:8080/forum/post', {
id: postId,
userId,
title: form.title,
content: form.content
})
ElMessage.success('更新成功')
} else {
// 新增帖子
await axios.post('http://localhost:8080/forum/post', {
userId,
title: form.title,
content: form.content
})
ElMessage.success('发布成功')
}
router.back()
} catch (err) {
ElMessage.error(isEdit.value ? '更新失败' : '发布失败')
} finally {
loading.value = false
}
})
}
const goBack = () => {
router.back()
}
onMounted(() => {
fetchPost()
})
</script>
<style scoped>
.post-edit-card {
max-width: 700px;
margin: 40px auto;
padding: 30px 40px;
}
.back-button {
margin-bottom: 20px;
font-size: 14px;
color: #409EFF;
cursor: pointer;
}
.title {
text-align: center;
margin-bottom: 30px;
font-weight: 600;
color: #303133;
}
</style>
说明
- 标题
maxlength="12" ,校验规则同步限制最多12字
- 正文
maxlength="600" ,校验规则同步限制最多600字
- 正文
<el-input type="textarea"> 自带自动换行支持,style="white-space: pre-wrap" 保证换行符保留显示
- 如果还想限制输入英文半角字符与中文汉字混合的字数精确,需用自定义校验函数,但这里按字符数限制符合一般需求
这样即可满足你“标题最多12字,正文600字,自动换行”的要求。
<h2 class="post-title">{{ post?.title }}</h2>
<p class="post-info">
作者: {{ post?.username || post?.userId }} |
发布时间: {{ formatDateTime(post?.createdAt) }}
</p>
<p class="post-content" style="white-space: pre-wrap">{{ post?.content }}</p>
<!-- 点赞 收藏 举报 按钮 -->
<div class="post-actions">
<button @click="toggleLike" :class="{ active: liked }" class="btn-like">
{{ liked ? "已点赞" : "点赞" }} ({{ likeCount }})
</button>
<button @click="toggleFavorite" :class="{ active: favorited }" class="btn-favorite">
{{ favorited ? "已收藏" : "收藏" }}
</button>
<button @click="openReportDialog" class="btn-report">
举报
</button>
</div>
<hr />
<h3>评论区</h3>
<div v-if="loadingComments" class="loading">加载评论中...</div>
<div v-else>
<ul class="comments-list">
<li v-for="comment in rootComments" :key="comment.id" class="comment-item">
<div class="comment-main">
<div class="comment-header">
<b>{{ comment.username || ("用户ID: " + comment.userId) }}</b>
<span v-if="comment.createdAt" class="comment-time"
>评论时间 {{ formatDateTime(comment.createdAt) }}</span
>
<button
v-if="comment.userId == userId"
@click="deleteComment(comment.id)"
class="btn-delete"
title="删除评论"
>
删除
</button>
<button @click="toggleReplyBox(comment.id)" class="btn-reply">
{{ replyingTo === comment.id ? "取消回复" : "回复" }}
</button>
<button @click="toggleRepliesCollapse(comment.id)" class="btn-collapse">
{{ repliesCollapsed[comment.id] ? "展开回复" : "收起回复" }}
</button>
</div>
<p class="comment-content" style="white-space: pre-wrap">{{ comment.content }}</p>
<div v-if="replyingTo === comment.id" class="reply-box">
<el-input
v-model="replyContent"
type="textarea"
:autosize="{ minRows: 2, maxRows: 12 }"
placeholder="回复内容"
style="width: 100%;"
class="autosize-textarea"
/>
<button class="btn-submit" @click="submitReply(comment.id)">提交回复</button>
</div>
</div>
<ul
v-if="!repliesCollapsed[comment.id] && flattenReplies[comment.id]?.length"
class="replies-list"
>
<li
v-for="reply in flattenReplies[comment.id]"
:key="reply.id"
class="comment-reply"
>
<div class="comment-header">
<b>{{ reply.username || ("用户ID: " + reply.userId) }}</b>
<span class="comment-time"
>回复时间 {{ formatDateTime(reply.createdAt) }}</span
>
<span class="reply-to" v-if="reply.parentCommentId">
回复 <b>{{ rootCommentUsernames[comment.id] }}</b>
</span>
<button
v-if="reply.userId == userId"
@click="deleteComment(reply.id)"
class="btn-delete"
title="删除回复"
>
删除
</button>
<button @click="toggleReplyBox(reply.id)" class="btn-reply">
{{ replyingTo === reply.id ? "取消回复" : "回复" }}
</button>
</div>
<p class="comment-content" style="white-space: pre-wrap">
{{ reply.content }}
</p>
<div v-if="replyingTo === reply.id" class="reply-box">
<el-input
v-model="replyContent"
type="textarea"
:autosize="{ minRows: 2, maxRows: 12 }"
placeholder="回复内容"
style="width: 100%;"
class="autosize-textarea"
/>
<button class="btn-submit" @click="submitReply(reply.id)">
提交回复
</button>
</div>
</li>
</ul>
</li>
</ul>
<hr />
<h4>发表评论</h4>
<el-input
v-model="newComment"
type="textarea"
:autosize="{ minRows: 3, maxRows: 12 }"
placeholder="请输入评论内容"
class="new-comment-textarea autosize-textarea"
style="width: 100%;"
/>
<button class="btn-submit" @click="submitComment">提交评论</button>
</div>
<el-dialog v-model="reportDialogVisible" title="举报帖子" width="400px">
<el-input
v-model="reportReason"
type="textarea"
:autosize="{ minRows: 4, maxRows: 12 }"
placeholder="请输入举报原因"
style="width: 100%;"
class="autosize-textarea"
/>
<span slot="footer" class="dialog-footer">
<el-button @click="reportDialogVisible = false">取消</el-button>
<el-button type="primary" @click="submitReport">提交举报</el-button>
</span>
</el-dialog>
改用等宽字体,保证每个字符宽度相同,视觉上每行字数基本一致,在文本框和显示内容上用 white-space: pre-wrap; 保持换行和空格一致。给我完整代码
<template>
<div class="post-detail">
<button @click="goBack" class="back-btn">返回主页</button>
<h2 class="post-title">{{ post?.title }}</h2>
<p class="post-info">
作者: {{ post?.username || post?.userId }} |
发布时间: {{ formatDateTime(post?.createdAt) }}
</p>
<p class="post-content monospace-content">{{ post?.content }}</p>
<!-- 点赞 收藏 举报 按钮 -->
<div class="post-actions">
<button @click="toggleLike" :class="{ active: liked }" class="btn-like">
{{ liked ? "已点赞" : "点赞" }} ({{ likeCount }})
</button>
<button @click="toggleFavorite" :class="{ active: favorited }" class="btn-favorite">
{{ favorited ? "已收藏" : "收藏" }}
</button>
<button @click="openReportDialog" class="btn-report">
举报
</button>
</div>
<hr />
<h3>评论区</h3>
<div v-if="loadingComments" class="loading">加载评论中...</div>
<div v-else>
<ul class="comments-list">
<li v-for="comment in rootComments" :key="comment.id" class="comment-item">
<div class="comment-main">
<div class="comment-header">
<b>{{ comment.username || ("用户ID: " + comment.userId) }}</b>
<span v-if="comment.createdAt" class="comment-time"
>评论时间 {{ formatDateTime(comment.createdAt) }}</span
>
<button
v-if="comment.userId == userId"
@click="deleteComment(comment.id)"
class="btn-delete"
title="删除评论"
>
删除
</button>
<button @click="toggleReplyBox(comment.id)" class="btn-reply">
{{ replyingTo === comment.id ? "取消回复" : "回复" }}
</button>
<button @click="toggleRepliesCollapse(comment.id)" class="btn-collapse">
{{ repliesCollapsed[comment.id] ? "展开回复" : "收起回复" }}
</button>
</div>
<p class="comment-content monospace-content">{{ comment.content }}</p>
<div v-if="replyingTo === comment.id" class="reply-box">
<el-input
v-model="replyContent"
type="textarea"
:autosize="{ minRows: 2, maxRows: 12 }"
placeholder="回复内容"
style="width: 100%;"
class="autosize-textarea monospace-textarea"
/>
<button class="btn-submit" @click="submitReply(comment.id)">提交回复</button>
</div>
</div>
<ul
v-if="!repliesCollapsed[comment.id] && flattenReplies[comment.id]?.length"
class="replies-list"
>
<li
v-for="reply in flattenReplies[comment.id]"
:key="reply.id"
class="comment-reply"
>
<div class="comment-header">
<b>{{ reply.username || ("用户ID: " + reply.userId) }}</b>
<span class="comment-time"
>回复时间 {{ formatDateTime(reply.createdAt) }}</span
>
<span class="reply-to" v-if="reply.parentCommentId">
回复 <b>{{ rootCommentUsernames[comment.id] }}</b>
</span>
<button
v-if="reply.userId == userId"
@click="deleteComment(reply.id)"
class="btn-delete"
title="删除回复"
>
删除
</button>
<button @click="toggleReplyBox(reply.id)" class="btn-reply">
{{ replyingTo === reply.id ? "取消回复" : "回复" }}
</button>
</div>
<p class="comment-content monospace-content">
{{ reply.content }}
</p>
<div v-if="replyingTo === reply.id" class="reply-box">
<el-input
v-model="replyContent"
type="textarea"
:autosize="{ minRows: 2, maxRows: 12 }"
placeholder="回复内容"
style="width: 100%;"
class="autosize-textarea monospace-textarea"
/>
<button class="btn-submit" @click="submitReply(reply.id)">
提交回复
</button>
</div>
</li>
</ul>
</li>
</ul>
<hr />
<h4>发表评论</h4>
<el-input
v-model="newComment"
type="textarea"
:autosize="{ minRows: 3, maxRows: 12 }"
placeholder="请输入评论内容"
class="new-comment-textarea autosize-textarea monospace-textarea"
style="width: 100%;"
/>
<button class="btn-submit" @click="submitComment">提交评论</button>
</div>
<el-dialog v-model="reportDialogVisible" title="举报帖子" width="400px">
<el-input
v-model="reportReason"
type="textarea"
:autosize="{ minRows: 4, maxRows: 12 }"
placeholder="请输入举报原因"
style="width: 100%;"
class="autosize-textarea monospace-textarea"
/>
<span slot="footer" class="dialog-footer">
<el-button @click="reportDialogVisible = false">取消</el-button>
<el-button type="primary" @click="submitReport">提交举报</el-button>
</span>
</el-dialog>
</div>
</template>
<script setup>
import { ref, computed, onMounted } from "vue";
import axios from "axios";
import { useRoute, useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import dayjs from "dayjs";
const formatDateTime = (isoString) => {
if (!isoString) return "";
return dayjs(isoString).format("YYYY年MM月DD日 HH:mm:ss");
};
const route = useRoute();
const router = useRouter();
const postId = Number(route.params.id);
const post = ref(null);
const comments = ref([]);
const loadingComments = ref(false);
const userId = localStorage.getItem("userId");
const newComment = ref("");
const replyingTo = ref(null);
const replyContent = ref("");
const repliesCollapsed = ref({});
// 点赞收藏举报相关
const liked = ref(false);
const likeCount = ref(0);
const favorited = ref(false);
const reportDialogVisible = ref(false);
const reportReason = ref("");
const fetchPost = async () => {
try {
const res = await axios.get(`http://localhost:8080/forum/post/${postId}`);
post.value = res.data;
likeCount.value = res.data.likeCount || 0;
} catch (error) {
ElMessage.error("加载帖子详情失败");
router.back();
}
};
const fetchComments = async () => {
loadingComments.value = true;
try {
const res = await axios.get(`http://localhost:8080/forum/comments/${postId}`);
comments.value = res.data;
} catch (error) {
ElMessage.error("加载评论失败");
} finally {
loadingComments.value = false;
}
};
const fetchLikeStatus = async () => {
if (!userId) return;
try {
const res = await axios.get(`http://localhost:8080/forum/post/like/status`, {
params: { userId, postId }
});
liked.value = res.data.liked;
} catch (error) {
console.error("查询点赞状态失败", error);
}
};
const fetchFavoriteStatus = async () => {
if (!userId) return;
try {
const res = await axios.get(`http://localhost:8080/forum/post/favorite/status`, {
params: { userId, postId }
});
favorited.value = res.data.favorited;
} catch (error) {
console.error("查询收藏状态失败", error);
}
};
const toggleRepliesCollapse = (commentId) => {
repliesCollapsed.value[commentId] = !repliesCollapsed.value[commentId];
};
const goBack = () => {
router.back();
};
const submitComment = async () => {
const content = newComment.value.trim();
if (!content) {
ElMessage.warning("请输入评论内容");
return;
}
try {
await axios.post("http://localhost:8080/forum/comment", {
postId,
userId,
content,
parentCommentId: null,
});
ElMessage.success("评论成功");
newComment.value = "";
fetchComments();
} catch (error) {
ElMessage.error("发表评论失败");
}
};
const toggleReplyBox = (commentId) => {
if (replyingTo.value === commentId) {
replyingTo.value = null;
replyContent.value = "";
} else {
replyingTo.value = commentId;
replyContent.value = "";
}
};
const submitReply = async (parentCommentId) => {
const content = replyContent.value.trim();
if (!content) {
ElMessage.warning("请输入回复内容");
return;
}
try {
await axios.post("http://localhost:8080/forum/comment", {
postId,
userId,
content,
parentCommentId,
});
ElMessage.success("回复成功");
replyingTo.value = null;
replyContent.value = "";
fetchComments();
} catch (error) {
ElMessage.error("回复失败");
}
};
const deleteComment = async (commentId) => {
try {
await ElMessageBox.confirm("确定删除此评论吗?", "提示", {
confirmButtonText: "确定",
cancelButtonText: "取消",
type: "warning",
});
await axios.delete(`http://localhost:8080/forum/comment/${commentId}`);
ElMessage.success("删除成功");
fetchComments();
} catch (error) {
if (error !== "cancel") {
ElMessage.error("删除失败");
}
}
};
const toggleLike = async () => {
if (!userId) {
ElMessage.warning("请先登录");
return;
}
try {
if (!liked.value) {
await axios.post("http://localhost:8080/forum/post/like", { userId, postId });
liked.value = true;
likeCount.value++;
ElMessage.success("点赞成功");
} else {
await axios.delete("http://localhost:8080/forum/post/like", { params: { userId, postId } });
liked.value = false;
likeCount.value--;
ElMessage.success("取消点赞成功");
}
} catch {
ElMessage.error("点赞操作失败");
}
};
const toggleFavorite = async () => {
if (!userId) {
ElMessage.warning("请先登录");
return;
}
try {
if (!favorited.value) {
await axios.post("http://localhost:8080/forum/post/favorite", { userId, postId });
favorited.value = true;
ElMessage.success("收藏成功");
} else {
await axios.delete("http://localhost:8080/forum/post/favorite", { params: { userId, postId } });
favorited.value = false;
ElMessage.success("取消收藏成功");
}
} catch {
ElMessage.error("收藏操作失败");
}
};
const openReportDialog = () => {
if (!userId) {
ElMessage.warning("请先登录");
return;
}
reportReason.value = "";
reportDialogVisible.value = true;
};
const submitReport = async () => {
if (!reportReason.value.trim()) {
ElMessage.warning("请输入举报原因");
return;
}
try {
await axios.post("http://localhost:8080/forum/post/report", {
reporterId: userId,
postId,
reason: reportReason.value,
});
ElMessage.success("举报成功,管理员会尽快处理");
reportDialogVisible.value = false;
} catch {
ElMessage.error("举报失败");
}
};
// 计算一级评论(parentCommentId === null)
const rootComments = computed(() =>
comments.value
.filter((c) => !c.parentCommentId)
.sort((a, b) => new Date(a.createdAt) - new Date(b.createdAt))
);
// flattenReplies: 二级及以上回复折叠到一级评论
const flattenReplies = computed(() => {
const map = {};
rootComments.value.forEach((root) => {
map[root.id] = [];
});
comments.value.forEach((c) => {
if (c.parentCommentId) {
let parentId = c.parentCommentId;
let current = comments.value.find((cc) => cc.id === parentId);
while (current && current.parentCommentId) {
parentId = current.parentCommentId;
current = comments.value.find((cc) => cc.id === parentId);
}
if (map[parentId]) {
map[parentId].push(c);
}
}
});
Object.values(map).forEach((list) =>
list.sort((a, b) => new Date(a.createdAt) - new Date(b.createdAt))
);
return map;
});
const rootCommentUsernames = computed(() => {
const map = {};
rootComments.value.forEach((root) => {
map[root.id] = root.username || `用户ID: ${root.userId}`;
});
return map;
});
onMounted(() => {
fetchPost();
fetchComments();
fetchLikeStatus();
fetchFavoriteStatus();
});
</script>
<style scoped>
.post-detail {
max-width: 800px;
margin: auto;
padding: 20px;
font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
color: #222;
background: #f9f9f9;
border-radius: 8px;
box-shadow: 0 4px 12px rgb(0 0 0 / 0.1);
}
.back-btn {
background: none;
border: none;
color: #409eff;
font-size: 16px;
cursor: pointer;
margin-bottom: 10px;
padding: 0;
transition: color 0.3s;
}
.back-btn:hover {
color: #66b1ff;
}
.post-title {
margin-bottom: 8px;
color: #303133;
font-weight: 700;
}
.post-info {
margin-bottom: 20px;
color: #909399;
font-size: 14px;
}
/* 内容显示用等宽字体,保留换行和空格 */
.post-content.monospace-content,
.comment-content.monospace-content {
font-family: monospace, "Courier New", Courier, monospace !important;
white-space: pre-wrap !important;
word-break: break-word !important;
overflow-wrap: break-word !important;
}
.post-content {
background: white;
padding: 16px;
border-radius: 6px;
margin-bottom: 30px;
line-height: 1.5;
box-shadow: inset 0 0 8px rgb(0 0 0 / 0.03);
}
.post-actions {
margin: 10px 0 20px;
display: flex;
gap: 12px;
}
.post-actions button {
display: flex;
align-items: center;
gap: 6px;
padding: 6px 14px;
background-color: #f0f2f5;
border: 1px solid #dcdfe6;
border-radius: 18px;
font-size: 14px;
font-weight: 600;
color: #606266;
cursor: pointer;
transition: all 0.3s ease;
user-select: none;
}
.btn-like.active,
.btn-favorite.active {
color: #f56c6c;
}
.comments-list,
.replies-list {
list-style-type: none;
padding-left: 0;
margin: 0;
}
.comment-item {
background: white;
border-radius: 6px;
padding: 14px 20px;
margin-bottom: 16px;
box-shadow: 0 1px 3px rgb(0 0 0 / 0.1);
}
.comment-main {
position: relative;
}
.comment-header {
display: flex;
align-items: center;
gap: 10px;
flex-wrap: wrap;
font-size: 14px;
margin-bottom: 8px;
}
.comment-header b {
color: #409eff;
font-weight: 600;
}
.comment-time {
color: #909399;
font-size: 12px;
}
.reply-to {
color: #606266;
font-size: 12px;
margin-left: 4px;
}
/* 评论文字等宽 */
.comment-content {
font-size: 15px;
color: #606266;
line-height: 1.5;
margin: 0;
padding-left: 4px;
}
/* 回复框及发表评论输入框等宽字体 */
.autosize-textarea.monospace-textarea .el-textarea__inner {
font-family: monospace, "Courier New", Courier, monospace !important;
white-space: pre-wrap !important;
word-break: break-word !important;
overflow-wrap: break-word !important;
resize: vertical;
}
.reply-box {
margin-top: 8px;
width: 100%;
}
/* 让 el-input 宽度撑满容器 */
.reply-box .autosize-textarea,
.new-comment-textarea.autosize-textarea {
width: 100%;
max-width: 100%;
box-sizing: border-box;
}
.btn-delete,
.btn-reply,
.btn-submit,
.btn-collapse {
background: none;
border: none;
color: #409eff;
cursor: pointer;
padding: 2px 6px;
border-radius: 4px;
font-size: 13px;
transition: background-color 0.3s;
user-select: none;
}
.btn-delete {
color: #f56c6c;
}
.btn-delete:hover {
background-color: #fde2e2;
}
.btn-reply:hover,
.btn-submit:hover,
.btn-collapse:hover {
background-color: #ecf5ff;
color: #66b1ff;
}
.reply-box .btn-submit {
margin-top: 6px;
font-weight: 600;
}
.replies-list {
margin-top: 10px;
padding-left: 30px;
border-left: 2px solid #ebeef5;
}
.comment-reply {
background: #f5f7fa;
border-radius: 6px;
padding: 10px 16px;
margin-bottom: 12px;
box-shadow: inset 0 1px 3px rgb(0 0 0 / 0.03);
}
.new-comment-textarea {
margin-bottom: 10px;
border-radius: 6px;
border: 1px solid #dcdfe6;
padding: 8px 10px;
font-size: 15px;
resize: vertical;
}
.btn-submit {
background-color: #409eff;
color: white;
border-radius: 4px;
padding: 8px 18px;
font-weight: 600;
transition: background-color 0.3s;
}
.btn-submit:hover {
background-color: #66b1ff;
}
.loading {
font-size: 16px;
color: #909399;
text-align: center;
padding: 20px 0;
}
.post-actions button:hover {
background-color: #e6f7ff;
border-color: #91d5ff;
color: #1890ff;
}
.post-actions button.active {
background-color: #bae7ff;
border-color: #40a9ff;
color: #096dd9;
box-shadow: 0 0 6px rgb(24 144 255 / 0.6);
}
/* 点赞按钮单独颜色 */
.btn-like {
color: #fa541c;
border-color: #ffa39e;
}
.btn-like.active {
background-color: #ffccc7;
border-color: #ff4d4f;
color: #a8071a;
box-shadow: 0 0 6px rgb(255 77 79 / 0.8);
}
/* 收藏按钮单独颜色 */
.btn-favorite {
color: #faad14;
border-color: #ffe58f;
}
.btn-favorite.active {
background-color: #fff7e6;
border-color: #ffc53d;
color: #ad6800;
box-shadow: 0 0 6px rgb(255 197 0 / 0.8);
}
/* 举报按钮采用警告色 */
.btn-report {
color: #f5222d;
border-color: #ffccc7;
}
.btn-report:hover {
background-color: #fff1f0;
border-color: #ff4d4f;
color: #a8071a;
box-shadow: 0 0 6px rgb(255 77 79 / 0.8);
}
</style>
说明
- 给帖子内容显示框和评论内容显示加了
.monospace-content 类,并用 CSS 设置等宽字体和 white-space: pre-wrap 保留换行和空格。
- 给所有用于输入的
el-input 的 textarea 加了 monospace-textarea 类,设置同样的等宽字体和换行。
- 保证换行符、空格字符在显示和输入时生效且字符宽度一致,视觉上每行字数更均匀,避免字宽不一导致“行内文字长度不均匀”。
- 保留你已有的 autosize 和宽度样式。
这样,文本框和显示的内容都会使用等宽字体,且换行和空格生效,视觉上每行字符数基本均匀。
(记得你后端存储和发送内容里应该使用真实换行符\n,而不是//换行//这种文本,否则换行不会生效。)