CREATE TABLE longtermmemory ( id INT AUTOINCREMENT PRIMARY… · The Chat Archive
Explore CREATE TABLE longtermmemory ( id INT AUTOINCREMENT PRIMARY KEY, userid INT NOT NULL,… Save Share Download ▾ ReportJump to turn (17) 1 CREATE TABLE longtermmemory ( id INT AUTOINCREMENT PRIMARY KEY, userid INT NOT N 2 接下来我会给你一份需求,但你一定要用上面两个表 3 Entity package com.example.springboot.entity; public class Study { private Integ 4 帮我生成 Postman 测试集合 JSON 5 短期记忆区域 查看已选单词 选择单词 {{ currentWord.word }} 🔊 发音 {{ currentWord.word }} 释义: {{ cu 6 package com.example.springboot.controller; import com.example.springboot.entity. 7 短期记忆区域 查看已选单词 选择单词 {{ currentWord.word }} 🔊 发音 {{ currentWord.word }} 释义: {{ cu 8 正面点击认识忘记只是触动翻转功能,不会传数据,背面点击忘记认识才会传数据给后端 9 短期记忆区域 查看已选单词 选择单词 {{ currentWord.word }} 🔊 发音 {{ currentWord.word }} 释义: {{ cu 10 短期记忆区域 查看已选单词 选择单词 {{ currentWord.word }} 🔊 发音 {{ currentWord.word }} 释义: {{ cu 11 package com.example.springboot.controller; import com.example.springboot.entity. 12 写修改后的完整 StudyMapper.xml 的selectReviewCandidates SQL,和修改后的 Vue 交互示例 13 短期记忆区域 查看已选单词 选择单词 {{ currentWord.word }} 🔊 发音 {{ currentWord.word }} 释义: {{ cu 14 短期记忆区域 查看已选单词 选择单词 {{ currentWord.word }} 🔊 发音 {{ currentWord.word }} 释义: {{ cu 15 点击忘记会减少次数 16 给我完整后的代码 17 短期记忆区域 查看已选单词 选择单词 {{ currentWord.word }} 🔊 发音 {{ currentWord.word }} 释义: {{ cu CREATE TABLE long_term_memory (
id INT AUTO_INCREMENT PRIMARY KEY,
user_id INT NOT NULL,
word_id INT NOT NULL,
review_count INT DEFAULT 0, -- 总复习次数
ease_factor FLOAT DEFAULT 2.5, -- 学习难度因子(如 SuperMemo 算法所需)
interval_days INT DEFAULT 0, -- 下次复习间隔(单位:天)
next_review_date DATE, -- 下一次复习的目标日期
last_review_date DATE, -- 上一次复习日期
last_score INT DEFAULT NULL, -- 上一次复习的记忆分数(例如 0-5)
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
code Copy code
FOREIGN KEY (user_id) REFERENCES user(id),
FOREIGN KEY (word_id) REFERENCES words(id),
UNIQUE(user_id, word_id)
);
CREATE TABLE user_word_memory (
id INT AUTO_INCREMENT PRIMARY KEY,
user_id INT NOT NULL,
word_id INT NOT NULL,
score INT DEFAULT 0,
last_seen INT DEFAULT -1,
FOREIGN KEY (user_id) REFERENCES user(id),
FOREIGN KEY (word_id) REFERENCES words(id),
UNIQUE(user_id, word_id)
);
Assistant
Copy first prompt Copy first response
Details
Provider OpenAI
Model provenance As recorded by source dataset
Turns 17 (34 messages)
Language zh
Conversation date Jun 8, 2025
Added to archive Nov 16, 2026
ID 01m7h42vn78fwbbd118qhc81fjSource & license Imported from WildChat-4.8M (AI2) (source ). Imported records earn no Research Points.
Upstream record: 2f803c3b5d25010593a8a1cae9dad7d4
Zhao et al., WildChat: 1M ChatGPT Interaction Logs in the Wild (ICLR 2024). Contains information from WildChat-4.8M, made available under the ODC Attribution License.
License: ODC-BY-1.0
2025-06-08 06:20 UTC Copy response
你设计了两个与单词记忆相关的表:
long_term_memory :存储用户对单词的长期记忆状态,包含诸如复习次数、难度因子、间隔天数、复习时间等信息,便于实现类似 SuperMemo 算法的间隔重复(Spaced Repetition)功能。
user_word_memory :存储用户对单词的简单记忆评分及最后一次出现的时间戳(用整数表示),相对更简单粗糙。
建议和改进
这两个表的功能有一定重合,都包含了 user_id 和 word_id 唯一约束,都涉及用户记忆单词的记录。建议明确区分两个表的设计目标,或者合并,避免数据冗余和同步问题。
如果你打算实现基于间隔重复的记忆机制,long_term_memory 的设计更为合适。
在 long_term_memory 表中,建议给 next_review_date 和 last_review_date 设置默认值(如 NULL),以避免不确定的值。
ease_factor 默认为 2.5 是符合 SuperMemo 算法的惯例。
last_score 定义成 INT DEFAULT NULL 可以,但也可考虑用更小的范围如 TINYINT。
user_word_memory 中的 last_seen 字段是整数,如果表示 UNIX 时间戳,建议明确字段注释,或者改用 DATETIME 类型。
合并示例(如果只使用一个表)
sql Copy code
CREATE TABLE user_word_longterm_memory (
id INT AUTO_INCREMENT PRIMARY KEY,
user_id INT NOT NULL,
word_id INT NOT NULL,
review_count INT DEFAULT 0,
ease_factor FLOAT DEFAULT 2.5,
interval_days INT DEFAULT 0,
next_review_date DATE DEFAULT NULL,
last_review_date DATE DEFAULT NULL,
last_score TINYINT DEFAULT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES user(id),
FOREIGN KEY (word_id) REFERENCES words(id),
UNIQUE(user_id, word_id)
);
如果你有具体业务逻辑,欢迎告诉我,我可以帮你设计更符合需求的表结构。
Assistant2025-06-08 06:22 UTC Copy response
明白了,请将需求发给我,我会根据你指定的两个表结构进行设计和实现。
Entity
package com.example.springboot.entity;
public class Study {
private Integer id;
private Integer userId;
private Integer wordId;
private Integer score;
private Integer lastSeen;
private String word; // 单词文本
private String definition; // 单词释义
code Copy code
// Getters and setters
public String getWord() { return word; }
public void setWord(String word) { this.word = word; }
public String getDefinition() { return definition; }
public void setDefinition(String definition) { this.definition = definition; }
public Integer getId() { return id; }
public void setId(Integer id) { this.id = id; }
public Integer getUserId() { return userId; }
public void setUserId(Integer userId) { this.userId = userId; }
public Integer getWordId() { return wordId; }
public void setWordId(Integer wordId) { this.wordId = wordId; }
public Integer getScore() { return score; }
public void setScore(Integer score) { this.score = score; }
public Integer getLastSeen() { return lastSeen; }
public void setLastSeen(Integer lastSeen) { this.lastSeen = lastSeen; }
}
Controller
package com.example.springboot.controller;
import com.example.springboot.service.StudyService;
import org.springframework.web.bind.annotation.*;
import org.springframework.http.ResponseEntity;
import org.springframework.http.HttpStatus;
import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("/study")
public class StudyController {
Show full message · 339 lines Assistant2025-06-08 06:22 UTC Copy response
好的!我理解你的需求是在现有系统基础上 ,融合如下基于user_word_memory和long_term_memory两张表的间隔复习算法逻辑,重点在于:
按照轮次(round)控制“冷却”和复习节奏;
利用score和last_seen字段对单词优先级排序复习;
达到掌握阈值后把单词“升入”long_term_memory表进行长期复习管理。
方案设计思路
你的user_word_memory表用于存放“新词(短期记忆)”状态,每轮学习主要从这里挑选“冷却期到”的单词复习;
达到pass_score(>=3)的单词写入long_term_memory表并从user_word_memory删去,表示单词进入“长期复习”阶段;
在长期复习阶段(long_term_memory表),可以单独设计复习策略,这里先保留该表接口占位,后续根据需求再具体实现。
代码层面设计步骤
1. 在StudyService里添加轮次复习主方法
Show full message · 219 lines Assistant2025-06-08 06:31 UTC Copy response
以下是根据你提供的接口设计,生成的一个基础 Postman Collection JSON,包含5个请求:
/study/select-words (POST) — 用户添加单词
/study/select-words (GET) — 获取已选单词
/study/pending-words (GET) — 获取待学习单词
/study/remove-word (POST) — 删除单个单词
/study/review-list (GET) — 获取当前轮复习单词列表
/study/review-result (POST) — 处理复习结果
你可以直接导入这个 JSON 到 Postman 进行测试,记得根据实际环境修改 baseUrl。
Show full message · 276 lines Assistant2025-06-08 06:44 UTC Copy response
你现在有一个功能完善的短期记忆前端(基于 user_word_memory),我帮你设计一个围绕【复习轮次 round】的算法流程,并完善交互。
重点思路:
每轮开始时,向后端请求当前轮可复习的单词(冷却完成,按score/lastSeen排序),取前N个
前端依次展示这些单词,用户选择“认识”或“忘记”,将结果发送到后端,后端更新score、lastSeen,必要时迁移到long_term_memory
复习完当前列表后,再请求下一批复习单词
轮次由前端管理(存本地/参数传递)
1. 前端算法状态扩展及主要方法补充
在你当前的 <script setup> 中补充:
js Copy code
// 新增复习相关状态
const round = ref(1) // 当前复习轮数
const reviewList = ref([]) // 当前轮复习单词列表
const reviewIndex = ref(0) // 当前待复习单词索引
const reviewing = ref(false) // 是否处于复习阶段
const N = 3 // 每轮复习单词数
// 查询当前轮次复习列表
const fetchReviewList = async () => {
const userId = localStorage.getItem('userId')
if (!userId) return ElMessage.warning("请先登录或设置 userId")
try {
const res = await axios.get('/study/review-list', {
params: { userId: Number(userId), round: round.value }
})
reviewList.value = res.data
reviewIndex.value = 0
if (reviewList.value.length === 0) {
reviewing.value = false
ElMessage.success("本轮复习已结束,无更多单词")
return
}
reviewing.value = true
currentIndex.value = -1 // 复习时当前Word和短期记忆列表不同,这里先重置主卡片
isFlipped.value = false
ElMessage.info(`开始第${round.value}轮复习,共${reviewList.value.length}个单词`)
reviewSpeakCurrent()
} catch (e) {
console.error(e)
ElMessage.error("获取复习单词失败")
}
}
// 复习阶段朗读当前单词
const reviewSpeakCurrent = () => {
if (reviewIndex.value >= 0 && reviewIndex.value < reviewList.value.length) {
speakWord(reviewList.value[reviewIndex.value].word)
}
}
// 处理用户对复习单词的反馈
const handleReviewAnswer = async (type) => {
if (!reviewing.value) return
const study = reviewList.value[reviewIndex.value]
const remembered = type === 'know'
try {
await axios.post('/study/review-result', {
userId: Number(localStorage.getItem('userId')),
wordId: study.wordId || study.id,
round: round.value,
remembered
})
// 更新本地score,模拟即时反馈(可选)
if (remembered) {
study.score = (study.score || 0) + 1
} else {
study.score = Math.max((study.score || 0) - 1, 0)
}
study.lastSeen = round.value
reviewIndex.value++
if (reviewIndex.value >= reviewList.value.length) {
// 本轮复习完毕
reviewing.value = false
round.value++
ElMessage.success(`第${round.value - 1}轮复习结束`)
// 复习完毕自动启动下一轮(可根据需要修改)
fetchReviewList()
} else {
isFlipped.value = false
reviewSpeakCurrent()
}
} catch (e) {
ElMessage.error("提交复习结果失败")
}
}
package com.example.springboot.controller;
import com.example.springboot.entity.Study;
import com.example.springboot.service.StudyService;
import org.springframework.web.bind.annotation.*;
import org.springframework.http.ResponseEntity;
import org.springframework.http.HttpStatus;
import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("/study")
public class StudyController {
code Copy code
@Resource
private StudyService studyService;
// 用户选择单词
@PostMapping("/select-words")
public ResponseEntity<?> userSelectWords(@RequestBody Map<String, Object> payload) {
Integer userId = (Integer) payload.get("userId");
List<Integer> wordIds = (List<Integer>) payload.get("wordIds");
if (userId == null || wordIds == null || wordIds.isEmpty()) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("参数错误");
}
int insertedCount = studyService.insertUserSelectedWords(userId, wordIds);
if (insertedCount == 0) {
return ResponseEntity.status(HttpStatus.CONFLICT).body("所有单词已存在,无需再添加");
}
return ResponseEntity.ok("成功添加 " + insertedCount + " 个新单词");
}
// 获取已经选择的单词列表
@GetMapping("/select-words")
public ResponseEntity<?> getSelectedWords(@RequestParam(value = "userId", required = false) String userIdStr) {
if (userIdStr == null || !userIdStr.matches("\d+")) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("缺少或非法的 userId");
}
Show full message · 423 lines Assistant2025-06-08 06:50 UTC Copy response
你的代码整体设计清晰,基本上能够实现你描述的算法逻辑。下面是分析和建议,帮助你确认功能的正确性与健壮性:
1. 关于算法核心实现
1)初始化阶段
你的insertUserSelectedWords()中,初始score=0,lastSeen=-1符合要求;
也有确保插入不重复的逻辑,满足加载词库。
2)主循环复习逻辑
你在getReviewList(userId, round)中,调用的是SQL:
sql Copy code
WHERE user_id = #{userId} AND #{round} - last_seen >= #{cooldown}
ORDER BY score ASC, last_seen ASC
LIMIT #{limit}
这条SQL严格按照算法筛选满足“冷却完成”的单词,且优先级排序合理,且限制数量,满足“筛选冷却单词”、“排序规则”和“复习处理”要求。
processReviewResult()处理用户反馈逻辑,正确地实现了:
认识时score+1
忘记时score-1,且分数不低于0
分数达到 PASS_SCORE=3 即迁移到long_term_memory,否则更新user_word_memory
同时更新lastSeen为当前轮次
moveToLongTermMemory()逻辑正确,填充了SuperMemo需要的初始字段。
2. 可能的优化和注意点
2.1 参数类型转换
你Controller中:
java Copy code
Integer userId = (Integer) payload.get("userId");
这种转换存在风向风险,如果请求体json解析时userId是Integer类型就没问题,如果转为Double可能异常。建议用如下安全方式转换或用DTO绑定,避免类型转换错误。
2.2 并发操作风险
由于复习结果更新涉及删除插入操作,要确保数据库的事务安全性,或者加业务层锁,避免多请求冲突或重复迁移。
2.3 评分边界
你的score未明确限定最大上限,是否允许超过PASS_SCORE可确认(目前影响不大)。
2.4 查询性能
如果user_word_memory数据量庞大,且复习轮数较大时,#{round} - last_seen >= #{cooldown}可能需要索引支持last_seen列,保证查询性能。
2.5 long_term_memory的长期复习更新逻辑
你现有代码只完成了从短期到长期的迁移,针对长期记忆表的复习安排、ease_factor调整、interval_days计算等没有实现,后续可根据SuperMemo算法进一步增强。
3. 小结
功能点 是否覆盖 备注 初始化词库,初始score及last_seen ✅ insertUserSelectedWords()筛选复习单词,满足冷却条件 ✅
Show full message · 350 lines Assistant2025-06-08 06:56 UTC Copy response
明白了!你前端要求结合后端算法完成“基于短期记忆+卡片翻转+分步复习”流程,具体为:
按后端算法动态拉取“短期记忆复习列表”(冷却判断+优先级排序+每轮3词)
卡片前面显示单词,点击“认识/忘记”,卡片翻转到背面,展示释义等信息
背面继续点击“认识/忘记”,反馈结果上传后端,刷新下一单词
依序复习完一轮单词后自动加载下一轮列表,直到空为止
以下是根据你的UI结构和需求改造的前端大体方案
1. 新增复习状态控制数据
js Copy code
// 轮数
const round = ref(1)
// 复习单词列表 当前轮次短期记忆单词(对象数组),包含word/definition等
const reviewList = ref([])
// 当前复习单词索引
const reviewIndex = ref(0)
// 卡片状态: false 表示前面(只显示word), true表示背面(显示释义等)
const isFlipped = ref(false)
// 当前复习单词,支持页面绑定
const currentWord = computed(() => {
return reviewList.value[reviewIndex.value] || {}
})
2. 新增复习流程相关函数
js Copy code
// 请求后端获取本轮待复习单词
const fetchReviewList = async () => {
const userId = localStorage.getItem('userId')
if (!userId) return ElMessage.warning("请先登录或设置 userId")
try {
const res = await axios.get('/study/review-list', {
params: { userId: Number(userId), round: round.value }
})
reviewList.value = res.data
reviewIndex.value = 0
isFlipped.value = false
if (reviewList.value.length === 0) {
ElMessage.success(`第${round.value}轮复习结束,无更多单词`)
// 清空复习状态,回显短期记忆正常列表(可选)
return
}
// 开始朗读第一个词
speakWord(currentWord.value.word)
} catch (e) {
ElMessage.error("加载复习单词失败")
console.error(e)
}
}
// 处理用户第一次点击按钮(正面 => 翻转背面)
const onFrontButtonClick = () => {
if (!isFlipped.value) {
// 前面点击,播放发音 + 翻转
speakWord(currentWord.value.word)
isFlipped.value = true
}
}
// 处理背面按钮点击(反馈给后端),然后显示下一个单词
const onBackButtonClick = async (type) => {
if (!isFlipped.value) return
const userId = localStorage.getItem('userId')
if (!userId) {
ElMessage.warning("请先登录或设置 userId")
return
}
try {
await axios.post('/study/review-result', {
userId: Number(userId),
wordId: currentWord.value.wordId || currentWord.value.id,
round: round.value,
remembered: type === 'know'
})
// 下一单词准备
reviewIndex.value++
if (reviewIndex.value >= reviewList.value.length) {
// 当前轮复习完成,准备下一轮
round.value++
await fetchReviewList()
}
isFlipped.value = false
if (reviewIndex.value < reviewList.value.length) {
speakWord(currentWord.value.word)
}
} catch (e) {
ElMessage.error("提交复习结果失败")
console.error(e)
}
}
正面点击认识忘记只是触动翻转功能,不会传数据,背面点击忘记认识才会传数据给后端
Assistant2025-06-08 06:58 UTC Copy response
明白你的需求:点击正面“认识/忘记”按钮只执行翻转(展示背面),不会传数据;点击背面“认识/忘记”按钮才真正提交复习结果给后端,并加载下一单词。
我根据这个流程调整代码,保持你现有UI结构及逻辑,重点是区分正反面点击事件,确保只有背面操作才调用后端。
完整关键改动示例
1. 修改按钮事件,区分正面和背面点击
vue Copy code
<div class="card-container" v-if="reviewList.length">
<div class="card-wrapper">
<div class="card" :class="{ flipped: isFlipped }">
<!-- 卡片正面 -->
<div class="card-face card-front">
<h1>{{ currentWord.word }}</h1>
<el-button
@click.stop="speakWord(currentWord.word)"
style="background-color: #ffffff; border-color: #ffffff; color: #000000; margin-top: 20px;"
>
🔊 发音
</el-button>
</div>
<!-- 卡片背面 -->
<div class="card-face card-back">
<h1>{{ currentWord.word }}</h1>
<p><strong>释义:</strong>{{ currentWord.definition }}</p>
<p><strong>发音:</strong>{{ currentWord.pronunciation || '暂无' }}</p>
<el-button
@click.stop="speakWord(currentWord.word)"
style="background-color: #ffffff; border-color: #ffffff; color: #000000; margin-top: 20px;"
>
🔊 发音
</el-button>
</div>
</div>
<div class="btn-group">
<!-- 正面点击只翻转 -->
<el-button
type="danger"
v-if="!isFlipped"
@click="flipCard"
>忘记</el-button>
<el-button
type="success"
v-if="!isFlipped"
@click="flipCard"
>认识</el-button>
<!-- 背面点击提交复习结果 -->
<el-button
type="danger"
v-if="isFlipped"
@click="submitReviewResult(false)"
>忘记</el-button>
<el-button
type="success"
v-if="isFlipped"
@click="submitReviewResult(true)"
>认识</el-button>
</div>
</div>
</div>
Show full message · 350 lines Assistant2025-06-08 06:59 UTC Copy response
Show full message · 412 lines Show full message · 431 lines Assistant2025-06-08 07:03 UTC Copy response
你好!
你提供的前端 Vue 代码和之前的后端实现,从整体结构和接口调用来看,是能够联动实现你描述的基于user_word_memory和long_term_memory两张表的间隔复习算法的。以下是详细分析:
1. 你前端代码满足的关键点
复习轮次控制 :前端维护了round变量,复习时传递到后端接口,有助于后端判断冷却条件(round - last_seen >= cooldown)。
复习列表拉取 :通过调用/study/review-list接口,在每轮开始时动态拉取满足冷却和优先级排序的前N个单词(默认N=3)。
卡片交互流程 :
正面点击“认识/忘记” 触发卡片翻转,展示背面释义,无数据提交。
背面点击“认识/忘记” 调用/study/review-result接口,将结果提交给后端。
复习列表顺序处理 :复习单词依次递增索引,复习完当前列表后自动请求下一轮列表,符合算法里的轮迭代主流程。
语音朗读 :当卡片展示单词时调用SpeechSynthesisUtterance读单词,增强学习体验。
2. 后端接口符合算法逻辑
GET /study/review-list接口根据userId和round参数,从user_word_memory里筛选出满足冷却条件的单词,按score和last_seen排序,取前N条。
POST /study/review-result更新单词的记忆分数和last_seen,当分数达到pass_score(3分)时,将单词转入long_term_memory表,符合算法掌握阈值的处理。
以上逻辑保证了单词的筛选、复习、晋级流程基本完整。
3. 可实现的算法细节
初始化阶段 由你在“用户选择单词”时表user_word_memory插入数据,初始score=0且last_seen=-1。
每轮复习 根据数据库计算冷却期和分数优先级,只拉取可复习单词,保证复习有节奏、有重点。
复习结果 对分数累加或扣减,使得不熟悉单词优先复习。
掌握后迁移 到长期记忆表,后续可以独立设计长期复习算法和计划。
4. 注意事项和建议
前端复习界面显示 当前只支持短期记忆复习,你可以后续拓展长期记忆回顾的功能。
轮次逻辑维护 由前端管理,需要确保用户刷新或多设备时状态同步(可存储轮次到服务端或本地)。
接口错误处理 建议更丰富,增加用户提示和请求重试等体验优化。
持久化和事务性保障 后端processReviewResult建议用事务保证数据一致性。
性能优化 如数据大时建立last_seen等索引,分页加载。
5. 总结
你基于该架构和代码,前后端接口设计合理,结合了异步复习流程和复习算法内核逻辑,能够基本实现题述的间隔复习算法需求。
若后续你需提升长期记忆算法复杂度,或增加复习数据统计,用户习惯学习模式调节,欢迎继续完善。
如果需要,我可以帮你:
编写针对长期记忆表的调度与算法示例
优化交互体验(复习进度、定时提醒等)
或者帮你设计更细粒度的错误处理和状态持久化方案
随时告诉我!祝开发顺利!😊
package com.example.springboot.controller;
import com.example.springboot.entity.Study;
import com.example.springboot.service.StudyService;
import org.springframework.web.bind.annotation.*;
import org.springframework.http.ResponseEntity;
import org.springframework.http.HttpStatus;
import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("/study")
public class StudyController {
code Copy code
@Resource
private StudyService studyService;
// 用户选择单词
@PostMapping("/select-words")
public ResponseEntity<?> userSelectWords(@RequestBody Map<String, Object> payload) {
Integer userId = (Integer) payload.get("userId");
List<Integer> wordIds = (List<Integer>) payload.get("wordIds");
if (userId == null || wordIds == null || wordIds.isEmpty()) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("参数错误");
}
int insertedCount = studyService.insertUserSelectedWords(userId, wordIds);
if (insertedCount == 0) {
return ResponseEntity.status(HttpStatus.CONFLICT).body("所有单词已存在,无需再添加");
}
return ResponseEntity.ok("成功添加 " + insertedCount + " 个新单词");
}
// 获取已经选择的单词列表
@GetMapping("/select-words")
public ResponseEntity<?> getSelectedWords(@RequestParam(value = "userId", required = false) String userIdStr) {
if (userIdStr == null || !userIdStr.matches("\d+")) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("缺少或非法的 userId");
}
Show full message · 816 lines Assistant2025-06-08 07:09 UTC Copy response
你好!针对你反馈的问题:
问题描述
卡片没有显示单词 内容;
点击“认识”和“忘记”按钮无反应 。
主要排查点及原因分析
1. 卡片不显示单词问题
reviewList可能为空 :
你的展示区域是v-if="reviewList.length",但如果后台/study/review-list接口返回数据为空数组或报错,前端没有数据,ui自然空白。
currentWord计算属性 :
你定义的是:
js Copy code
const currentWord = computed(() => reviewList.value[reviewIndex.value] || {})
若reviewList或reviewIndex无效,会导致空对象,卡片显示空白。
确认后台接口真实返回数据格式 :
后端getReviewList接口返回的是List<Study>,而Study实体里看起来只有:
java Copy code
private Integer id;
private Integer userId;
private Integer wordId;
private Integer score;
private Integer lastSeen;
private String word; // 单词文本
private String definition; // 单词释义
但这里可能没被正确填充word和definition字段,或者你调用的 SQL/ORM 查询没有把单词文本查出来,只返回了user_word_memory的浅层数据。
解决方案:
确保复习列表接口返回足够详实的单词信息(word, definition) 。你当前selectReviewCandidates的 SQL:
sql Copy code
SELECT id, user_id AS userId, word_id AS wordId, score, last_seen AS lastSeen
FROM user_word_memory
WHERE user_id = #{userId} AND #{round} - last_seen >= #{cooldown}
ORDER BY score ASC, last_seen ASC
LIMIT #{limit}
只查了user_word_memory表,没有 join words表以获取word和definition字段。
你需要改成下面这种带 join 的SQL,返回单词详细信息:
写修改后的完整 StudyMapper.xml 的selectReviewCandidates SQL,和修改后的 Vue 交互示例
Assistant2025-06-08 07:11 UTC Copy response
下面给出:
修改后的 StudyMapper.xml 里 selectReviewCandidates 的完整 SQL ,包含 words 表关联,确保返回 word、definition、pronunciation 字段;
Vue 前端交互关键部分示例 ,符合你的需求,区分正面点击翻转,背面点击提交复习结果,并跳转下一单词。
1. 修改后完整的 StudyMapper.xml 里的 selectReviewCandidates
xml Copy code
<select id="selectReviewCandidates" resultType="com.example.springboot.entity.Study" parameterType="map">
SELECT
um.id,
um.user_id AS userId,
um.word_id AS wordId,
um.score,
um.last_seen AS lastSeen,
w.word,
w.definition,
w.pronunciation
FROM user_word_memory um
JOIN words w ON um.word_id = w.id
WHERE um.user_id = #{userId} AND (#{round} - um.last_seen) >= #{cooldown}
ORDER BY um.score ASC, um.last_seen ASC
LIMIT #{limit}
</select>
说明 :
user_word_memory 表别名为 um
words 表别名为 w,关联 um.word_id = w.id
查询字段包含学习用户单词进度字段与单词本身详细字段
按照学习分数升序、最近复习时间升序排序筛选满足冷却的单词
返回数量有限制保证每轮复习单词数为 limit
2. Vue 前端交互示例(核心复习卡片部分)
Show full message · 411 lines Assistant2025-06-08 07:13 UTC Copy response
Show full message · 422 lines Show full message · 420 lines Assistant2025-06-08 07:33 UTC Copy response
你说的“背面认识点击计数”需求,可以通过给 reviewList 里的每个单词增加一个本地计数字段 rememberCount 来实现。每当用户背面点击“认识” ,这个字段就加1,展示在卡片左上角。
这里是详细方案和示例代码:
1. 增加 rememberCount
reviewList 中的每个对象增加字段:rememberCount (初始为0)
每次背面点击“认识”,对应单词的 rememberCount 自增1
2. Vue代码修改示例
Assistant2025-06-08 07:35 UTC Copy response
你可以在 submitReviewResult 函数中,添加背面点击“忘记”时将当前单词的计数 rememberCount 减 1(下限为 0),同时“认识”时累加,如下示例:
js Copy code
const submitReviewResult = async (remembered) => {
const userId = localStorage.getItem('userId')
if (!userId) {
ElMessage.warning("请先登录或设置 userId")
return
}
try {
await axios.post('/study/review-result', {
userId: Number(userId),
wordId: currentWord.value.wordId || currentWord.value.id,
round: round.value,
remembered: remembered
})
if (remembered) {
// 认识时计数加1
reviewList.value[reviewIndex.value].rememberCount =
(reviewList.value[reviewIndex.value].rememberCount || 0) + 1
} else {
// 忘记时计数减1,最小为0
reviewList.value[reviewIndex.value].rememberCount = Math.max(
(reviewList.value[reviewIndex.value].rememberCount || 0) - 1,
0
)
}
reviewIndex.value++
isFlipped.value = false
if (reviewIndex.value >= reviewList.value.length) {
round.value++
await fetchReviewList()
}
if (reviewIndex.value < reviewList.value.length) {
speakWord(currentWord.value.word)
}
} catch (e) {
ElMessage.error("提交复习结果失败")
console.error(e)
}
}
这样“忘记”操作即可让计数减少,且不会低于 0。
你可以把这个代码替换到之前的 submitReviewResult 里即可实现你需求。
Assistant2025-06-08 07:38 UTC Copy response
Show full message · 422 lines Show full message · 420 lines Assistant2025-06-08 07:45 UTC Copy response
你可以在卡片正面左上角显示当前单词的score,只需要在模板中添加一个展示区域,绑定 currentWord.score 即可。完整示例如下:
vue Copy code
<template>
<el-row style="height: 100vh; padding: 20px;" :gutter="20">
<!-- 左侧:学习单词区域 -->
<el-col :span="12" class="left-panel" style="height: 100%;">
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
<h2>短期记忆区域</h2>
<div>
<el-button type="primary" @click="openSelectedDialog">查看已选单词</el-button>
<el-button type="success" @click="openDialog" style="margin-left: 10px;">选择单词</el-button>
</div>
</div>
<!-- 单词卡片 -->
<div class="card-container" v-if="reviewList.length">
<div class="card-wrapper">
<div class="card" :class="{ flipped: isFlipped }">
<!-- 卡片正面 -->
<div class="card-face card-front">
<!-- 这里添加score展示 -->
<div class="score-badge">
记忆分数: {{ currentWord.score || 0 }}
</div>
<h1>{{ currentWord.word }}</h1>
<el-button
@click.stop="speakWord(currentWord.word)"
style="background-color: #ffffff; border-color: #ffffff; color: #000000; margin-top: 20px;"
>
🔊 发音
</el-button>
</div>
<!-- 卡片背面 -->
<div class="card-face card-back">
<h1>{{ currentWord.word }}</h1>
<p><strong>释义:</strong>{{ currentWord.definition }}</p>
<el-button
@click.stop="speakWord(currentWord.word)"
style="background-color: #ffffff; border-color: #ffffff; color: #000000; margin-top: 20px;"
>
🔊 发音
</el-button>
</div>
</div>
<div class="btn-group">
<el-button type="danger" v-if="!isFlipped" @click="flipCard">忘记</el-button>
<el-button type="success" v-if="!isFlipped" @click="flipCard">认识</el-button>
<el-button type="danger" v-if="isFlipped" @click="submitReviewResult(false)">忘记</el-button>
<el-button type="success" v-if="isFlipped" @click="submitReviewResult(true)">认识</el-button>
</div>
</div>
</div>
<!-- 无复习单词提示 -->
<div v-else style="text-align:center; margin-top: 50px; font-size: 20px; color: #999;">
无可复习单词,复习完成!
</div>
<!-- 省略...已选单词弹窗、选择单词弹窗等 -->
</el-col>
<!-- 右侧内容省略 -->
</el-row>
</template>
<script setup>
// 这里假设你已经声明了 currentWord,reviewList 等逻辑,保持不变即可
</script>
<style scoped>
.score-badge {
position: absolute;
top: 10px;
left: 10px;
font-size: 14px;
color: #409EFF; /* Element UI 主色 */
font-weight: 600;
background: #ecf5ff;
padding: 4px 8px;
border-radius: 4px;
user-select: none;
z-index: 10;
}
</style>
Not yet included in a published release.
@Resource
private StudyService studyService;
// 用户选择单词
@PostMapping("/select-words")
public ResponseEntity<?> userSelectWords(@RequestBody Map<String, Object> payload) {
Integer userId = (Integer) payload.get("userId");
List<Integer> wordIds = (List<Integer>) payload.get("wordIds");
if (userId == null || wordIds == null || wordIds.isEmpty()) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("参数错误");
}
int insertedCount = studyService.insertUserSelectedWords(userId, wordIds);
if (insertedCount == 0) {
return ResponseEntity.status(HttpStatus.CONFLICT).body("所有单词已存在,无需再添加");
}
return ResponseEntity.ok("成功添加 " + insertedCount + " 个新单词");
}
// 获取已经选择的单词列表
@GetMapping("/select-words")
public ResponseEntity<?> getSelectedWords(@RequestParam(value = "userId", required = false) String userIdStr) {
if (userIdStr == null || !userIdStr.matches("\d+")) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("缺少或非法的 userId");
}
code Copy code
Integer userId = Integer.valueOf(userIdStr);
return ResponseEntity.ok(studyService.getSelectedWordsByUserId(userId));
}
// 获取用户可选的未学习单词(用于前端弹窗选择)
@GetMapping("/pending-words")
public ResponseEntity<?> getPendingWords(
@RequestParam("userId") Integer userId,
@RequestParam(value = "limit", defaultValue = "100") Integer limit) {
return ResponseEntity.ok(studyService.getPendingWords(userId, limit));
}
// 删除用户选择的单词
@PostMapping("/remove-word")
public ResponseEntity<?> removeWord(@RequestBody Map<String, Object> payload) {
Integer userId = (Integer) payload.get("userId");
Integer wordId = (Integer) payload.get("wordId");
if (userId == null || wordId == null) {
return ResponseEntity.badRequest().body("参数错误");
}
int rows = studyService.deleteWord(userId, wordId);
if (rows > 0) {
return ResponseEntity.ok("删除成功");
} else {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body("未找到单词");
}
}
// 批量删除用户选择的单词
@PostMapping("/remove-words")
public ResponseEntity<?> removeWords(@RequestBody Map<String, Object> payload) {
Integer userId = (Integer) payload.get("userId");
List<Integer> wordIds = (List<Integer>) payload.get("wordIds");
if (userId == null || wordIds == null || wordIds.isEmpty()) {
return ResponseEntity.badRequest().body("参数错误");
}
int rows = studyService.deleteWords(userId, wordIds);
if (rows > 0) {
return ResponseEntity.ok("批量删除成功");
} else {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body("未找到单词");
}
}
Service
package com.example.springboot.service;
import com.example.springboot.entity.Study;
import com.example.springboot.entity.Word;
import com.example.springboot.mapper.StudyMapper;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
@Service
public class StudyService {
code Copy code
@Resource
private StudyMapper studyMapper;
// 用户手动选择单词加入记忆
public int insertUserSelectedWords(Integer userId, List<Integer> wordIds) {
int count = 0;
for (Integer wordId : wordIds) {
Study exist = studyMapper.selectStudyByUserIdAndWordId(userId, wordId);
if (exist == null) {
Study study = new Study();
study.setUserId(userId);
study.setWordId(wordId);
study.setScore(0);
study.setLastSeen(-1);
studyMapper.insertStudy(study);
count++;
}
}
return count;
}
// 获取用户选择的单词
public List<Word> getSelectedWordsByUserId(Integer userId) {
return studyMapper.selectSelectedWordsByUserId(userId);
}
// 获取待背单词
public List<Study> getPendingWords(Integer userId, int limit) {
return studyMapper.selectPendingWordsFromPlan(userId, limit);
}
// 删除单词
public int deleteWord(Integer userId, Integer wordId) {
return studyMapper.deleteStudyByUserIdAndWordId(userId, wordId);
}
// 批量删除
public int deleteWords(Integer userId, List<Integer> wordIds) {
return studyMapper.deleteStudiesByUserIdAndWordIds(userId, wordIds);
}
Mapper
package com.example.springboot.mapper;
import com.example.springboot.entity.Study;
import com.example.springboot.entity.Word;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
@Mapper
public interface StudyMapper {
code Copy code
// 从user_word_plan抽取指定数量且user_word_memory中不存在的单词
List<Study> selectPendingWordsFromPlan(@Param("userId") Integer userId, @Param("limit") int limit);
// 查询 user_word_memory 中对应记录
Study selectStudyByUserIdAndWordId(@Param("userId") Integer userId, @Param("wordId") Integer wordId);
// 插入 user_word_memory
int insertStudy(Study study);
// 更新 user_word_memory
int updateStudy(Study study);
// 查询单词详情
Word selectWordById(@Param("id") Integer id);
// 查询某个用户的所有已选单词详细信息
List<Word> selectSelectedWordsByUserId(@Param("userId") Integer userId);
// 单个删除
int deleteStudyByUserIdAndWordId(@Param("userId") Integer userId, @Param("wordId") Integer wordId);
// 批量删除
int deleteStudiesByUserIdAndWordIds(@Param("userId") Integer userId, @Param("wordIds") List<Integer> wordIds);
code Copy code
<!-- 从 user_word_plan 中抽取待学习且 user_word_memory 中不存在的单词 -->
<select id="selectPendingWordsFromPlan" parameterType="map" resultType="com.example.springboot.entity.Study">
SELECT
NULL AS id,
up.user_id AS userId,
up.word_id AS wordId,
w.word AS word,
w.definition AS definition,
0 AS score,
-1 AS lastSeen
FROM user_word_plan up
JOIN words w ON up.word_id = w.id
LEFT JOIN user_word_memory um ON up.user_id = um.user_id AND up.word_id = um.word_id
WHERE up.user_id = #{userId} AND up.status = 'pending' AND um.id IS NULL
ORDER BY up.added_at ASC
LIMIT #{limit}
</select>
<!-- 查询 user_word_memory -->
<select id="selectStudyByUserIdAndWordId" parameterType="map" resultType="com.example.springboot.entity.Study">
SELECT id, user_id AS userId, word_id AS wordId, score, last_seen AS lastSeen
FROM user_word_memory
WHERE user_id = #{userId} AND word_id = #{wordId}
</select>
<!-- 插入 user_word_memory -->
<insert id="insertStudy" parameterType="com.example.springboot.entity.Study" useGeneratedKeys="true" keyProperty="id">
INSERT INTO user_word_memory(user_id, word_id, score, last_seen)
VALUES(#{userId}, #{wordId}, #{score}, #{lastSeen})
</insert>
<!-- 更新 user_word_memory -->
<update id="updateStudy" parameterType="com.example.springboot.entity.Study">
UPDATE user_word_memory
SET score = #{score},
last_seen = #{lastSeen}
WHERE id = #{id}
</update>
<!-- 查询单词详情 -->
<select id="selectWordById" parameterType="int" resultType="com.example.springboot.entity.Word">
SELECT id, word, definition, pronunciation, custom_content AS customContent, created_at AS createdAt
FROM words
WHERE id = #{id}
</select>
<!-- 查询用户已选择的单词 -->
<select id="selectSelectedWordsByUserId" parameterType="int" resultType="com.example.springboot.entity.Word">
SELECT
w.id,
w.word,
w.definition,
w.pronunciation,
w.custom_content AS customContent,
w.created_at AS createdAt
FROM user_word_memory uwm
JOIN words w ON uwm.word_id = w.id
WHERE uwm.user_id = #{userId}
</select>
<!-- 删除单个单词 -->
<delete id="deleteStudyByUserIdAndWordId" parameterType="map">
DELETE FROM user_word_memory WHERE user_id = #{userId} AND word_id = #{wordId}
</delete>
<!-- 批量删除单词 -->
<delete id="deleteStudiesByUserIdAndWordIds" parameterType="map">
DELETE FROM user_word_memory WHERE user_id = #{userId} AND word_id IN
<foreach item="wordId" collection="wordIds" open="(" separator="," close=")">
#{wordId}
</foreach>
</delete>
@Service
public class StudyService {
@Resource
private StudyMapper studyMapper;
@Resource
private LongTermMemoryMapper longTermMemoryMapper;
private static final int COOLDOWN = 2;
private static final int PASS_SCORE = 3;
private static final int N = 3;
/**
* 获取当前轮次可复习单词列表(冷却结束且优先级最高的N个)
* @param userId 用户ID
* @param round 当前轮次
* @return 待复习单词列表
*/
public List<Study> getReviewList(Integer userId, int round) {
// 筛选 user_word_memory表中满足冷却条件的单词并排序,取前N个
return studyMapper.selectReviewCandidates(userId, round, COOLDOWN, N);
}
/**
* 处理用户对单词的复习反馈
* @param userId 用户ID
* @param wordId 单词ID
* @param currentRound 当前轮次
* @param remembered 是否记住(true表示认识,false表示忘记)
*/
public void processReviewResult(Integer userId, Integer wordId, int currentRound, boolean remembered) {
Study study = studyMapper.selectStudyByUserIdAndWordId(userId, wordId);
if (study == null) return;
int newScore = study.getScore();
if (remembered) {
newScore += 1;
} else {
newScore = Math.max(newScore - 1, 0);
}
if (newScore >= PASS_SCORE) {
// 达标,迁移到 long_term_memory
moveToLongTermMemory(study, currentRound, newScore);
studyMapper.deleteStudyByUserIdAndWordId(userId, wordId);
} else {
// 未达标,更新score及last_seen,留在 user_word_memory
study.setScore(newScore);
study.setLastSeen(currentRound);
studyMapper.updateStudy(study);
}
}
/**
* 新单词迁移到长期记忆表,初始各字段赋值
*/
private void moveToLongTermMemory(Study study, int currentRound, int score) {
// 创建 long_term_memory 实例(假设有相应实体类LongTermMemory)
LongTermMemory ltm = new LongTermMemory();
ltm.setUserId(study.getUserId());
ltm.setWordId(study.getWordId());
ltm.setReviewCount(1);
ltm.setEaseFactor(2.5f);
ltm.setIntervalDays(0);
ltm.setLastReviewDate(java.sql.Date.valueOf(java.time.LocalDate.now())); // 设置为当天
ltm.setNextReviewDate(java.sql.Date.valueOf(java.time.LocalDate.now().plusDays(1))); // 初始下一天复习
ltm.setLastScore(score);
longTermMemoryMapper.insertLongTermMemory(ltm);
}
// 你已有的其他方法...
}
2. Mapper接口和XML补充
StudyMapper.java 新增方法:java Copy code
// 根据冷却轮数筛选出符合条件的单词,排序返回前N个
List<Study> selectReviewCandidates(@Param("userId") Integer userId,
@Param("round") int round,
@Param("cooldown") int cooldown,
@Param("limit") int limit);
StudyMapper.xml新增xml Copy code
<select id="selectReviewCandidates" resultType="com.example.springboot.entity.Study" parameterType="map">
SELECT id, user_id AS userId, word_id AS wordId, score, last_seen AS lastSeen
FROM user_word_memory
WHERE user_id = #{userId} AND #{round} - last_seen >= #{cooldown}
ORDER BY score ASC, last_seen ASC
LIMIT #{limit}
</select>
3. LongTermMemory实体和Mapper示例 为了调用方便,补充LongTermMemory实体类:
java Copy code
public class LongTermMemory {
private Integer id;
private Integer userId;
private Integer wordId;
private Integer reviewCount; // 总复习次数
private Float easeFactor; // 学习难度因子
private Integer intervalDays; // 下次复习间隔
private java.sql.Date nextReviewDate;
private java.sql.Date lastReviewDate;
private Integer lastScore;
// getters/setters...
}
java Copy code
@Mapper
public interface LongTermMemoryMapper {
int insertLongTermMemory(LongTermMemory ltm);
}
xml Copy code
<insert id="insertLongTermMemory" parameterType="com.example.springboot.entity.LongTermMemory" useGeneratedKeys="true" keyProperty="id">
INSERT INTO long_term_memory(user_id, word_id, review_count, ease_factor, interval_days, next_review_date, last_review_date, last_score)
VALUES(#{userId}, #{wordId}, #{reviewCount}, #{easeFactor}, #{intervalDays}, #{nextReviewDate}, #{lastReviewDate}, #{lastScore})
</insert>
4. Controller增加复习相关接口示范 java Copy code
@RestController
@RequestMapping("/study")
public class StudyController {
@Resource
private StudyService studyService;
// 获取当前轮复习列表
@GetMapping("/review-list")
public ResponseEntity<?> getReviewList(@RequestParam Integer userId, @RequestParam Integer round) {
List<Study> reviewList = studyService.getReviewList(userId, round);
return ResponseEntity.ok(reviewList);
}
// 处理复习结果
@PostMapping("/review-result")
public ResponseEntity<?> postReviewResult(@RequestBody Map<String, Object> payload) {
Integer userId = (Integer) payload.get("userId");
Integer wordId = (Integer) payload.get("wordId");
Integer round = (Integer) payload.get("round");
Boolean remembered = (Boolean) payload.get("remembered");
if (userId == null || wordId == null || round == null || remembered == null) {
return ResponseEntity.badRequest().body("参数错误");
}
studyService.processReviewResult(userId, wordId, round, remembered);
return ResponseEntity.ok("复习结果处理成功");
}
// 之前接口保留…
}
总结
从user_word_memory表筛选冷却完毕的单词,限量复习;
根据用户反馈更新分数和上次复习轮次;
达到掌握标记则迁移单词到long_term_memory,开始长期复习;
初始化长期复习信息,并设计长期复习计划和后续接口;
如果你需要,我可以帮你写完整的LongTermMemory实体、Mapper实现等,或者做长期复习的调度与算法设计。欢迎随时告诉我!
{
"info": {
"_postman_id": "b1b343db-1f45-4e13-b221-2f23249dbd0f",
"name": "Study API Collection",
"description": "测试学习系统相关接口",
"schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json"
},
"item": [
{
"name": "添加用户选择的单词",
"request": {
"method": "POST",
"header": [
{
"key": "Content-Type",
"value": "application/json"
}
],
"body": {
"mode": "raw",
"raw": "{\n \"userId\": 1,\n \"wordIds\": [101, 102, 103]\n}"
},
"url": {
"raw": "{{baseUrl}}/study/select-words",
"host": [
"{{baseUrl}}"
],
"path": [
"study",
"select-words"
]
}
},
"response": []
},
{
"name": "获取用户已选单词",
"request": {
"method": "GET",
"header": [],
"url": {
"raw": "{{baseUrl}}/study/select-words?userId=1",
"host": [
"{{baseUrl}}"
],
"path": [
"study",
"select-words"
],
"query": [
{
"key": "userId",
"value": "1"
}
]
}
},
"response": []
},
{
"name": "获取待学习单词",
"request": {
"method": "GET",
"header": [],
"url": {
"raw": "{{baseUrl}}/study/pending-words?userId=1&limit=10",
"host": [
"{{baseUrl}}"
],
"path": [
"study",
"pending-words"
],
"query": [
{
"key": "userId",
"value": "1"
},
{
"key": "limit",
"value": "10"
}
]
}
},
"response": []
},
{
"name": "删除用户单词",
"request": {
"method": "POST",
"header": [
{
"key": "Content-Type",
"value": "application/json"
}
],
"body": {
"mode": "raw",
"raw": "{\n \"userId\": 1,\n \"wordId\": 101\n}"
},
"url": {
"raw": "{{baseUrl}}/study/remove-word",
"host": [
"{{baseUrl}}"
],
"path": [
"study",
"remove-word"
]
}
},
"response": []
},
{
"name": "获取当前轮复习单词列表",
"request": {
"method": "GET",
"header": [],
"url": {
"raw": "{{baseUrl}}/study/review-list?userId=1&round=5",
"host": [
"{{baseUrl}}"
],
"path": [
"study",
"review-list"
],
"query": [
{
"key": "userId",
"value": "1"
},
{
"key": "round",
"value": "5"
}
]
}
},
"response": []
},
{
"name": "提交复习结果",
"request": {
"method": "POST",
"header": [
{
"key": "Content-Type",
"value": "application/json"
}
],
"body": {
"mode": "raw",
"raw": "{\n \"userId\": 1,\n \"wordId\": 101,\n \"round\": 5,\n \"remembered\": true\n}"
},
"url": {
"raw": "{{baseUrl}}/study/review-result",
"host": [
"{{baseUrl}}"
],
"path": [
"study",
"review-result"
]
}
},
"response": []
}
]
}
使用说明
导入时,Postman 会提示你导入此JSON文件作为一个集合
请在Postman的环境变量里自行定义 baseUrl,比如http://localhost:8080/api
如果你需要,我可以帮你生成更多请求示例或者带断言的测试用例!
<!-- 左侧:短期记忆区域 -->
<el-col :span="12" class="left-panel" style="height: 100%;">
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
<h2>短期记忆区域</h2>
<div>
<el-button type="primary" @click="openSelectedDialog">查看已选单词</el-button>
<el-button type="success" @click="openDialog" style="margin-left: 10px;">选择单词</el-button>
</div>
</div>
<!-- 单词卡片 -->
<div class="card-container" v-if="selectedWords.length">
<div class="card-wrapper">
<div class="card" :class="{ flipped: isFlipped }">
<div class="card-face card-front">
<h1>{{ currentWord.word }}</h1>
<el-button
@click.stop="speakWord(currentWord.word)"
style="background-color: #ffffff; border-color: #ffffff; color: #000000; margin-top: 20px;"
>
🔊 发音
</el-button>
</div>
<div class="card-face card-back">
<h1>{{ currentWord.word }}</h1>
<p><strong>释义:</strong>{{ currentWord.definition }}</p>
<p><strong>发音:</strong>{{ currentWord.pronunciation || '暂无' }}</p>
<el-button
@click.stop="speakWord(currentWord.word)"
style="background-color: #ffffff; border-color: #ffffff; color: #000000; margin-top: 20px;"
>
🔊 发音
</el-button>
</div>
</div>
<div class="btn-group">
<el-button type="danger" @click="handleButtonClick('forget')">忘记</el-button>
<el-button type="success" @click="handleButtonClick('know')">认识</el-button>
</div>
</div>
</div>
<!-- 已选单词弹窗 -->
<el-dialog v-model="selectedDialogVisible" title="已选单词列表" width="800px">
<el-table :data="selectedWords" style="width: 100%;" border @selection-change="handleSelectedChange">
<el-table-column type="selection" width="55" />
<el-table-column prop="id" label="ID" width="80" />
<el-table-column prop="word" label="单词" />
<el-table-column prop="definition" label="释义" />
<el-table-column label="操作" width="100">
<template #default="scope">
<el-button type="danger" size="small" @click="removeWord(scope.row)">删除</el-button>
</template>
</el-table-column>
</el-table>
<template #footer>
<span class="dialog-footer">
<el-button @click="selectedDialogVisible = false">关闭</el-button>
<el-button type="danger" :disabled="!selectedToDelete.length" @click="batchRemoveWords">
批量删除({{ selectedToDelete.length }})
</el-button>
</span>
</template>
</el-dialog>
</el-col>
<!-- 右侧:暂时不开发 -->
<el-col :span="12" class="right-panel" style="border: 1px solid #eee; padding: 20px;">
<h2>暂未开发</h2>
<p>暂未开发</p>
</el-col>
<!-- 弹窗:选择待学习单词 -->
<el-dialog v-model="dialogVisible" title="选择待学习单词" width="600px">
<el-table :data="pendingWords" style="width: 100%;" @selection-change="handleSelectionChange">
<el-table-column type="selection" width="55" />
<el-table-column prop="word" label="单词" />
<el-table-column prop="definition" label="释义" />
</el-table>
<template #footer>
<span class="dialog-footer">
<el-button @click="dialogVisible = false">取消</el-button>
<el-button type="primary" @click="submitSelectedWords">
确认选择({{ selectedToAdd.length }})
</el-button>
</span>
</template>
</el-dialog>
这是我的前端,现在根据端口,帮我实现算法。一、算法核心逻辑总结
初始化阶段
加载词库,为每个单词设置初始值:
score=0(分数,衡量熟练度),last_seen=-1(最后复习轮数,-1 表示未复习)。
全局参数:
cooldown=2(冷却轮数,复习后需间隔至少 2 轮才会再次出现)
pass_score=3(掌握阈值,分数≥3 时标记为 “已掌握”)
N=3(每轮复习前 N 个单词,可动态调整)
主循环逻辑(轮次迭代)
筛选冷却单词:
条件:当前轮数(round) - 单词.last_seen ≥ cooldown
含义:确保单词距离上一次复习已过足够轮数,避免频繁重复。
排序规则:
一级优先级:按score升序(低分优先,薄弱单词优先复习)。
二级优先级:若分数相同,按last_seen升序(冷却时间越久越优先)。
复习处理:
选取排序后的前 N 个单词,逐个展示并获取用户回答。
认识:score+1,若score≥pass_score则将已掌握单词放入“长期复习表”,每隔若干轮重新抽查;否则保留,记录last_seen=当前轮数。
忘记:score-1,记录last_seen=当前轮数,冷却结束后因低分优先复习。
终止条件:
当复习列表(review_list)为空时,流程结束。
2. 模板绑定补充 vue Copy code
<!-- 切换卡片区域,如果正在复习,显示复习列表卡片,否则显示短期记忆卡片 -->
<div class="card-container" v-if="reviewing">
<!-- 复习卡片 -->
<div class="card-wrapper">
<div class="card" :class="{ flipped: isFlipped }">
<div class="card-face card-front">
<h1>{{ reviewList[reviewIndex]?.word || '' }}</h1>
<el-button
@click.stop="speakWord(reviewList[reviewIndex]?.word)"
style="background-color: #ffffff; border-color: #ffffff; color: #000000; margin-top: 20px;"
>
🔊 发音
</el-button>
</div>
<div class="card-face card-back">
<h1>{{ reviewList[reviewIndex]?.word || '' }}</h1>
<p><strong>释义:</strong>{{ reviewList[reviewIndex]?.definition || '' }}</p>
<el-button
@click.stop="speakWord(reviewList[reviewIndex]?.word)"
style="background-color: #ffffff; border-color: #ffffff; color: #000000; margin-top: 20px;"
>
🔊 发音
</el-button>
</div>
</div>
<div class="btn-group">
<el-button type="danger" @click="handleReviewAnswer('forget')">忘记</el-button>
<el-button type="success" @click="handleReviewAnswer('know')">认识</el-button>
</div>
</div>
</div>
<div class="card-container" v-else-if="selectedWords.length">
<!-- 你已有的短期记忆显示卡片,略 -->
</div>
3. 页面加载或按钮触发开始复习 vue Copy code
<el-button type="warning" @click="fetchReviewList" style="margin-left: 10px;">开始复习</el-button>
4. 后端接口提醒
GET /study/review-list?userId=xxx&round=xxx 返回符合算法条件的单词列表;
POST /study/review-result 接收 {userId, wordId, round, remembered},处理分数和转入长期记忆逻辑;
5. 代码说明
round由前端管理,并传给接口,这样后端知道当前复习轮次,结合 cooldown 计算哪些单词可复习;
筛选逻辑和排序逻辑写在后端SQL里,前端仅负责请求和交互;
每轮复习只能复习前N个单词,用户依次答题;
根据答案调用接口,听取后端反馈,这里假设接口成功即可本地更新;
轮次+复习单词变动,会触发界面切换和朗读,模拟真实复习体验。
如果你需要,我可以帮你写后端相关接口示例代码和数据库查询,也能帮你优化体验,比如添加复习进度条、倒计时等。欢迎告诉我你的进一步需求!
Integer userId = Integer.valueOf(userIdStr);
return ResponseEntity.ok(studyService.getSelectedWordsByUserId(userId));
}
// 获取用户可选的未学习单词(用于前端弹窗选择)
@GetMapping("/pending-words")
public ResponseEntity<?> getPendingWords(
@RequestParam("userId") Integer userId,
@RequestParam(value = "limit", defaultValue = "100") Integer limit) {
return ResponseEntity.ok(studyService.getPendingWords(userId, limit));
}
// 删除用户选择的单词
@PostMapping("/remove-word")
public ResponseEntity<?> removeWord(@RequestBody Map<String, Object> payload) {
Integer userId = (Integer) payload.get("userId");
Integer wordId = (Integer) payload.get("wordId");
if (userId == null || wordId == null) {
return ResponseEntity.badRequest().body("参数错误");
}
int rows = studyService.deleteWord(userId, wordId);
if (rows > 0) {
return ResponseEntity.ok("删除成功");
} else {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body("未找到单词");
}
}
// 批量删除用户选择的单词
@PostMapping("/remove-words")
public ResponseEntity<?> removeWords(@RequestBody Map<String, Object> payload) {
Integer userId = (Integer) payload.get("userId");
List<Integer> wordIds = (List<Integer>) payload.get("wordIds");
if (userId == null || wordIds == null || wordIds.isEmpty()) {
return ResponseEntity.badRequest().body("参数错误");
}
int rows = studyService.deleteWords(userId, wordIds);
if (rows > 0) {
return ResponseEntity.ok("批量删除成功");
} else {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body("未找到单词");
}
}
// 获取当前轮复习列表
@GetMapping("/review-list")
public ResponseEntity<?> getReviewList(@RequestParam Integer userId, @RequestParam Integer round) {
List<Study> reviewList = studyService.getReviewList(userId, round);
return ResponseEntity.ok(reviewList);
}
// 处理复习结果
@PostMapping("/review-result")
public ResponseEntity<?> postReviewResult(@RequestBody Map<String, Object> payload) {
Integer userId = (Integer) payload.get("userId");
Integer wordId = (Integer) payload.get("wordId");
Integer round = (Integer) payload.get("round");
Boolean remembered = (Boolean) payload.get("remembered");
if (userId == null || wordId == null || round == null || remembered == null) {
return ResponseEntity.badRequest().body("参数错误");
}
studyService.processReviewResult(userId, wordId, round, remembered);
return ResponseEntity.ok("复习结果处理成功");
}
}
package com.example.springboot.service;
import com.example.springboot.entity.LongTermMemory;
import com.example.springboot.entity.Study;
import com.example.springboot.entity.Word;
import com.example.springboot.mapper.LongTermMemoryMapper;
import com.example.springboot.mapper.StudyMapper;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
@Service
public class StudyService {
code Copy code
@Resource
private StudyMapper studyMapper;
@Resource
private LongTermMemoryMapper longTermMemoryMapper;
private static final int COOLDOWN = 2;
private static final int PASS_SCORE = 3;
private static final int N = 3;
/**
* 获取当前轮次可复习单词列表(冷却结束且优先级最高的N个)
* @param userId 用户ID
* @param round 当前轮次
* @return 待复习单词列表
*/
public List<Study> getReviewList(Integer userId, int round) {
// 筛选 user_word_memory表中满足冷却条件的单词并排序,取前N个
return studyMapper.selectReviewCandidates(userId, round, COOLDOWN, N);
}
/**
* 处理用户对单词的复习反馈
* @param userId 用户ID
* @param wordId 单词ID
* @param currentRound 当前轮次
* @param remembered 是否记住(true表示认识,false表示忘记)
*/
public void processReviewResult(Integer userId, Integer wordId, int currentRound, boolean remembered) {
Study study = studyMapper.selectStudyByUserIdAndWordId(userId, wordId);
if (study == null) return;
int newScore = study.getScore();
if (remembered) {
newScore += 1;
} else {
newScore = Math.max(newScore - 1, 0);
}
if (newScore >= PASS_SCORE) {
// 达标,迁移到 long_term_memory
moveToLongTermMemory(study, currentRound, newScore);
studyMapper.deleteStudyByUserIdAndWordId(userId, wordId);
} else {
// 未达标,更新score及last_seen,留在 user_word_memory
study.setScore(newScore);
study.setLastSeen(currentRound);
studyMapper.updateStudy(study);
}
}
/**
* 新单词迁移到长期记忆表,初始各字段赋值
*/
private void moveToLongTermMemory(Study study, int currentRound, int score) {
// 创建 long_term_memory 实例(假设有相应实体类LongTermMemory)
LongTermMemory ltm = new LongTermMemory();
ltm.setUserId(study.getUserId());
ltm.setWordId(study.getWordId());
ltm.setReviewCount(1);
ltm.setEaseFactor(2.5f);
ltm.setIntervalDays(0);
ltm.setLastReviewDate(java.sql.Date.valueOf(java.time.LocalDate.now())); // 设置为当天
ltm.setNextReviewDate(java.sql.Date.valueOf(java.time.LocalDate.now().plusDays(1))); // 初始下一天复习
ltm.setLastScore(score);
longTermMemoryMapper.insertLongTermMemory(ltm);
}
// 用户手动选择单词加入记忆
public int insertUserSelectedWords(Integer userId, List<Integer> wordIds) {
int count = 0;
for (Integer wordId : wordIds) {
Study exist = studyMapper.selectStudyByUserIdAndWordId(userId, wordId);
if (exist == null) {
Study study = new Study();
study.setUserId(userId);
study.setWordId(wordId);
study.setScore(0);
study.setLastSeen(-1);
studyMapper.insertStudy(study);
count++;
}
}
return count;
}
// 获取用户选择的单词
public List<Word> getSelectedWordsByUserId(Integer userId) {
return studyMapper.selectSelectedWordsByUserId(userId);
}
// 获取待背单词
public List<Study> getPendingWords(Integer userId, int limit) {
return studyMapper.selectPendingWordsFromPlan(userId, limit);
}
// 删除单词
public int deleteWord(Integer userId, Integer wordId) {
return studyMapper.deleteStudyByUserIdAndWordId(userId, wordId);
}
// 批量删除
public int deleteWords(Integer userId, List<Integer> wordIds) {
return studyMapper.deleteStudiesByUserIdAndWordIds(userId, wordIds);
}
}
package com.example.springboot.mapper;
import com.example.springboot.entity.Study;
import com.example.springboot.entity.Word;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
@Mapper
public interface StudyMapper {
code Copy code
// 从user_word_plan抽取指定数量且user_word_memory中不存在的单词
List<Study> selectPendingWordsFromPlan(@Param("userId") Integer userId, @Param("limit") int limit);
// 查询 user_word_memory 中对应记录
Study selectStudyByUserIdAndWordId(@Param("userId") Integer userId, @Param("wordId") Integer wordId);
// 插入 user_word_memory
int insertStudy(Study study);
// 更新 user_word_memory
int updateStudy(Study study);
// 查询单词详情
Word selectWordById(@Param("id") Integer id);
// 查询某个用户的所有已选单词详细信息
List<Word> selectSelectedWordsByUserId(@Param("userId") Integer userId);
// 单个删除
int deleteStudyByUserIdAndWordId(@Param("userId") Integer userId, @Param("wordId") Integer wordId);
// 批量删除
int deleteStudiesByUserIdAndWordIds(@Param("userId") Integer userId, @Param("wordIds") List<Integer> wordIds);
// 根据冷却轮数筛选出符合条件的单词,排序返回前N个
List<Study> selectReviewCandidates(@Param("userId") Integer userId,
@Param("round") int round,
@Param("cooldown") int cooldown,
@Param("limit") int limit);
code Copy code
<!-- 从 user_word_plan 中抽取待学习且 user_word_memory 中不存在的单词 -->
<select id="selectPendingWordsFromPlan" parameterType="map" resultType="com.example.springboot.entity.Study">
SELECT
NULL AS id,
up.user_id AS userId,
up.word_id AS wordId,
w.word AS word,
w.definition AS definition,
0 AS score,
-1 AS lastSeen
FROM user_word_plan up
JOIN words w ON up.word_id = w.id
LEFT JOIN user_word_memory um ON up.user_id = um.user_id AND up.word_id = um.word_id
WHERE up.user_id = #{userId} AND up.status = 'pending' AND um.id IS NULL
ORDER BY up.added_at ASC
LIMIT #{limit}
</select>
<!-- 查询 user_word_memory -->
<select id="selectStudyByUserIdAndWordId" parameterType="map" resultType="com.example.springboot.entity.Study">
SELECT id, user_id AS userId, word_id AS wordId, score, last_seen AS lastSeen
FROM user_word_memory
WHERE user_id = #{userId} AND word_id = #{wordId}
</select>
<!-- 插入 user_word_memory -->
<insert id="insertStudy" parameterType="com.example.springboot.entity.Study" useGeneratedKeys="true" keyProperty="id">
INSERT INTO user_word_memory(user_id, word_id, score, last_seen)
VALUES(#{userId}, #{wordId}, #{score}, #{lastSeen})
</insert>
<!-- 更新 user_word_memory -->
<update id="updateStudy" parameterType="com.example.springboot.entity.Study">
UPDATE user_word_memory
SET score = #{score},
last_seen = #{lastSeen}
WHERE id = #{id}
</update>
<!-- 查询单词详情 -->
<select id="selectWordById" parameterType="int" resultType="com.example.springboot.entity.Word">
SELECT id, word, definition, pronunciation, custom_content AS customContent, created_at AS createdAt
FROM words
WHERE id = #{id}
</select>
<!-- 查询用户已选择的单词 -->
<select id="selectSelectedWordsByUserId" parameterType="int" resultType="com.example.springboot.entity.Word">
SELECT
w.id,
w.word,
w.definition,
w.pronunciation,
w.custom_content AS customContent,
w.created_at AS createdAt
FROM user_word_memory uwm
JOIN words w ON uwm.word_id = w.id
WHERE uwm.user_id = #{userId}
</select>
<!-- 删除单个单词 -->
<delete id="deleteStudyByUserIdAndWordId" parameterType="map">
DELETE FROM user_word_memory WHERE user_id = #{userId} AND word_id = #{wordId}
</delete>
<!-- 批量删除单词 -->
<delete id="deleteStudiesByUserIdAndWordIds" parameterType="map">
DELETE FROM user_word_memory WHERE user_id = #{userId} AND word_id IN
<foreach item="wordId" collection="wordIds" open="(" separator="," close=")">
#{wordId}
</foreach>
</delete>
<select id="selectReviewCandidates" resultType="com.example.springboot.entity.Study" parameterType="map">
SELECT id, user_id AS userId, word_id AS wordId, score, last_seen AS lastSeen
FROM user_word_memory
WHERE user_id = #{userId} AND #{round} - last_seen >= #{cooldown}
ORDER BY score ASC, last_seen ASC
LIMIT #{limit}
</select>
import com.example.springboot.entity.LongTermMemory;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface LongTermMemoryMapper {
int insertLongTermMemory(LongTermMemory ltm);
}
代码有错吗?能实现下面的算法吗?一、算法核心逻辑总结
初始化阶段
加载词库,为每个单词设置初始值:
score=0(分数,衡量熟练度),last_seen=-1(最后复习轮数,-1 表示未复习)。
全局参数:
cooldown=2(冷却轮数,复习后需间隔至少 2 轮才会再次出现)
pass_score=3(掌握阈值,分数≥3 时标记为 “已掌握”)
N=3(每轮复习前 N 个单词,可动态调整)
主循环逻辑(轮次迭代)
筛选冷却单词:
条件:当前轮数(round) - 单词.last_seen ≥ cooldown
含义:确保单词距离上一次复习已过足够轮数,避免频繁重复。
排序规则:
一级优先级:按score升序(低分优先,薄弱单词优先复习)。
二级优先级:若分数相同,按last_seen升序(冷却时间越久越优先)。
复习处理:
选取排序后的前 N 个单词,逐个展示并获取用户回答。
认识:score+1,若score≥pass_score则将已掌握单词放入“长期复习表”,每隔若干轮重新抽查;否则保留,记录last_seen=当前轮数。
忘记:score-1,记录last_seen=当前轮数,冷却结束后因低分优先复习。
终止条件:
当复习列表(review_list)为空时,流程结束。
selectReviewCandidates SQL完成
按score和last_seen排序 ✅ SQL排序条件完备
控制每轮复习单词数 ✅ LIMIT #{limit}有效
复习结果对score调整 ✅ processReviewResult()正确实现
达标迁移长期记忆表 ✅ 迁移逻辑完整(含时间字段初始化)
复习列表空时终止 需前端控制 你后端返回空时,前端应识别停止复习流。
4. 代码示例建议
可添加@Transactional注解保证processReviewResult操作原子,避免并发写脏数据:
java Copy code
import org.springframework.transaction.annotation.Transactional;
@Service
public class StudyService {
...
@Transactional
public void processReviewResult(Integer userId, Integer wordId, int currentRound, boolean remembered) {
...
}
}
Controller建议用统一DTO替代Map<String,Object>收参,保证类型安全。
5. 总的来说 你的代码框架和SQL基本匹配需求算法,功能上是可以正常工作的。
长期复习相关(long_term_memory表的后续调度)和并发控制等可以作为后续优化重点。
如需,我可以帮你写一份Spring事务安全版本代码或长期复习管理示例,欢迎告知!
<!-- 左侧:学习单词区域 -->
<el-col :span="12" class="left-panel" style="height: 100%;">
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
<h2>短期记忆区域</h2>
<div>
<el-button type="primary" @click="openSelectedDialog">查看已选单词</el-button>
<el-button type="success" @click="openDialog" style="margin-left: 10px;">选择单词</el-button>
</div>
</div>
<!-- 单词卡片 -->
<div class="card-container" v-if="selectedWords.length">
<div class="card-wrapper">
<div class="card" :class="{ flipped: isFlipped }">
<div class="card-face card-front">
<h1>{{ currentWord.word }}</h1>
<el-button
@click.stop="speakWord(currentWord.word)"
style="background-color: #ffffff; border-color: #ffffff; color: #000000; margin-top: 20px;"
>
🔊 发音
</el-button>
</div>
<div class="card-face card-back">
<h1>{{ currentWord.word }}</h1>
<p><strong>释义:</strong>{{ currentWord.definition }}</p>
<p><strong>发音:</strong>{{ currentWord.pronunciation || '暂无' }}</p>
<el-button
@click.stop="speakWord(currentWord.word)"
style="background-color: #ffffff; border-color: #ffffff; color: #000000; margin-top: 20px;"
>
🔊 发音
</el-button>
</div>
</div>
<div class="btn-group">
<el-button type="danger" @click="handleButtonClick('forget')">忘记</el-button>
<el-button type="success" @click="handleButtonClick('know')">认识</el-button>
</div>
</div>
</div>
<!-- 已选单词弹窗 -->
<el-dialog v-model="selectedDialogVisible" title="已选单词列表" width="800px">
<el-table :data="selectedWords" style="width: 100%;" border @selection-change="handleSelectedChange">
<el-table-column type="selection" width="55" />
<el-table-column prop="id" label="ID" width="80" />
<el-table-column prop="word" label="单词" />
<el-table-column prop="definition" label="释义" />
<el-table-column label="操作" width="100">
<template #default="scope">
<el-button type="danger" size="small" @click="removeWord(scope.row)">删除</el-button>
</template>
</el-table-column>
</el-table>
<template #footer>
<span class="dialog-footer">
<el-button @click="selectedDialogVisible = false">关闭</el-button>
<el-button type="danger" :disabled="!selectedToDelete.length" @click="batchRemoveWords">
批量删除({{ selectedToDelete.length }})
</el-button>
</span>
</template>
</el-dialog>
</el-col>
<!-- 右侧:区域 -->
<el-col :span="12" class="right-panel" style="border: 1px solid #eee; padding: 20px;">
<h2>暂未开发</h2>
<p>暂未开发</p>
</el-col>
<!-- 弹窗:选择待学习单词 -->
<el-dialog v-model="dialogVisible" title="选择待学习单词" width="600px">
<el-table :data="pendingWords" style="width: 100%;" @selection-change="handleSelectionChange">
<el-table-column type="selection" width="55" />
<el-table-column prop="word" label="单词" />
<el-table-column prop="definition" label="释义" />
</el-table>
<template #footer>
<span class="dialog-footer">
<el-button @click="dialogVisible = false">取消</el-button>
<el-button type="primary" @click="submitSelectedWords">
确认选择({{ selectedToAdd.length }})
</el-button>
</span>
</template>
</el-dialog>
根据上面的后端代码,完善我前端代码。这是我的需求:左边是短期记忆的部分,卡片按着算法显示单词,一个卡片旋转特效,卡片正面写着英文单词,点击卡片下方任意按钮(忘记/认识),卡片翻转到背面,显示英文单词,释义,发音。用户看完后,继续点击卡片下方任意按钮(忘记/认识),然后传数据给后端处理算法,然后进行单词的复习顺序
3. 调整模板,对卡片、按钮绑定事件区分「正面点击」与「背面点击」 vue Copy code
<div class="card-container" v-if="reviewList.length">
<div class="card-wrapper">
<div class="card" :class="{ flipped: isFlipped }">
<div class="card-face card-front">
<h1>{{ currentWord.word }}</h1>
<el-button
@click.stop="onFrontButtonClick"
style="background-color: #ffffff; border-color: #ffffff; color: #000000; margin-top: 20px;"
>
🔊 发音
</el-button>
</div>
<div class="card-face card-back">
<h1>{{ currentWord.word }}</h1>
<p><strong>释义:</strong>{{ currentWord.definition }}</p>
<p><strong>发音:</strong>{{ currentWord.pronunciation || '暂无' }}</p>
<el-button
@click.stop="speakWord(currentWord.word)"
style="background-color: #ffffff; border-color: #ffffff; color: #000000; margin-top: 20px;"
>
🔊 发音
</el-button>
</div>
</div>
<div class="btn-group">
<el-button
type="danger"
@click="isFlipped ? onBackButtonClick('forget') : onFrontButtonClick()"
>
忘记
</el-button>
<el-button
type="success"
@click="isFlipped ? onBackButtonClick('know') : onFrontButtonClick()"
>
认识
</el-button>
</div>
</div>
</div>
<!-- 你之前的短期记忆列表卡片逻辑区域根据需要保留或隐藏 -->
4. 初始化自动触发复习(比如在 onMounted) js Copy code
onMounted(() => {
// 预热语音
speechSynthesis.speak(new SpeechSynthesisUtterance(' '))
// 加载复习列表开始复习
fetchReviewList()
})
5. speakWord 函数保持不变,适当控制朗读节奏即可。
小结
复习单词来源于后端接口(冷却和优先级判断后返回)
单词复习时先显示正面,点击认识/忘记,卡片翻转显示背面释义
背面点击同样按钮,提交结果到后端,进入下个单词循环
一轮完成自动加载下一轮,直到无待复习单词提示完成
如果你需要,我可以帮你写完整的前端代码补充或更新vue组件代码片段。你也可以告诉我想要增加的功能,比如“复习进度条”,“倒计时”,“学习数据统计”等。
2. JS逻辑代码对应修改 js Copy code
// 控制卡片翻转,正面点击后调用
const flipCard = () => {
speakWord(currentWord.value.word)
isFlipped.value = true
}
// 提交复习结果,背面点击后调用
const submitReviewResult = async (remembered) => {
const userId = localStorage.getItem('userId')
if (!userId) {
ElMessage.warning("请先登录或设置 userId")
return
}
try {
await axios.post('/study/review-result', {
userId: Number(userId),
wordId: currentWord.value.wordId || currentWord.value.id,
round: round.value,
remembered: remembered
})
// 下一个单词
reviewIndex.value++
isFlipped.value = false
if (reviewIndex.value >= reviewList.value.length) {
round.value++
await fetchReviewList()
}
if (reviewIndex.value < reviewList.value.length) {
speakWord(currentWord.value.word)
}
} catch (e) {
ElMessage.error("提交复习结果失败")
console.error(e)
}
}
3. 补充加载复习列表函数(可参考) js Copy code
const fetchReviewList = async () => {
const userId = localStorage.getItem('userId')
if (!userId) return ElMessage.warning("请先登录或设置 userId")
try {
const res = await axios.get('/study/review-list', {
params: { userId: Number(userId), round: round.value }
})
reviewList.value = res.data
reviewIndex.value = 0
isFlipped.value = false
if (reviewList.value.length === 0) {
ElMessage.success(`第${round.value}轮复习结束,无更多单词`)
return
}
speakWord(currentWord.value.word)
} catch (e) {
ElMessage.error("加载复习单词失败")
console.error(e)
}
}
4. 初始化调用(如在 onMounted) js Copy code
onMounted(() => {
speechSynthesis.speak(new SpeechSynthesisUtterance(' '))
fetchReviewList()
})
总结
正面按钮点击:只执行卡片翻转显示背面,无任何数据交互
背面按钮点击:触发复习结果提交请求,并切换至下一单词
依次复习一轮的N个单词后自动请求下一轮,直到无复习单词为止
如果需要,我可以帮你写一个完整的示例代码文件,或者帮你集成“复习进度条”“统计”等功能!
<!-- 左侧:学习单词区域 -->
<el-col :span="12" class="left-panel" style="height: 100%;">
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
<h2>短期记忆区域</h2>
<div>
<el-button type="primary" @click="openSelectedDialog">查看已选单词</el-button>
<el-button type="success" @click="openDialog" style="margin-left: 10px;">选择单词</el-button>
</div>
</div>
<!-- 单词卡片 -->
<div class="card-container" v-if="selectedWords.length">
<div class="card-wrapper">
<div class="card" :class="{ flipped: isFlipped }">
<div class="card-face card-front">
<h1>{{ currentWord.word }}</h1>
<el-button
@click.stop="speakWord(currentWord.word)"
style="background-color: #ffffff; border-color: #ffffff; color: #000000; margin-top: 20px;"
>
🔊 发音
</el-button>
</div>
<div class="card-face card-back">
<h1>{{ currentWord.word }}</h1>
<p><strong>释义:</strong>{{ currentWord.definition }}</p>
<p><strong>发音:</strong>{{ currentWord.pronunciation || '暂无' }}</p>
<el-button
@click.stop="speakWord(currentWord.word)"
style="background-color: #ffffff; border-color: #ffffff; color: #000000; margin-top: 20px;"
>
🔊 发音
</el-button>
</div>
</div>
<div class="btn-group">
<el-button type="danger" @click="handleButtonClick('forget')">忘记</el-button>
<el-button type="success" @click="handleButtonClick('know')">认识</el-button>
</div>
</div>
</div>
<!-- 已选单词弹窗 -->
<el-dialog v-model="selectedDialogVisible" title="已选单词列表" width="800px">
<el-table :data="selectedWords" style="width: 100%;" border @selection-change="handleSelectedChange">
<el-table-column type="selection" width="55" />
<el-table-column prop="id" label="ID" width="80" />
<el-table-column prop="word" label="单词" />
<el-table-column prop="definition" label="释义" />
<el-table-column label="操作" width="100">
<template #default="scope">
<el-button type="danger" size="small" @click="removeWord(scope.row)">删除</el-button>
</template>
</el-table-column>
</el-table>
<template #footer>
<span class="dialog-footer">
<el-button @click="selectedDialogVisible = false">关闭</el-button>
<el-button type="danger" :disabled="!selectedToDelete.length" @click="batchRemoveWords">
批量删除({{ selectedToDelete.length }})
</el-button>
</span>
</template>
</el-dialog>
</el-col>
<!-- 右侧:区域 -->
<el-col :span="12" class="right-panel" style="border: 1px solid #eee; padding: 20px;">
<h2>暂未开发</h2>
<p>暂未开发</p>
</el-col>
<!-- 弹窗:选择待学习单词 -->
<el-dialog v-model="dialogVisible" title="选择待学习单词" width="600px">
<el-table :data="pendingWords" style="width: 100%;" @selection-change="handleSelectionChange">
<el-table-column type="selection" width="55" />
<el-table-column prop="word" label="单词" />
<el-table-column prop="definition" label="释义" />
</el-table>
<template #footer>
<span class="dialog-footer">
<el-button @click="dialogVisible = false">取消</el-button>
<el-button type="primary" @click="submitSelectedWords">
确认选择({{ selectedToAdd.length }})
</el-button>
</span>
</template>
</el-dialog>
<template>
<el-row style="height: 100vh; padding: 20px;" :gutter="20">
<!-- 左侧:学习单词区域 -->
<el-col :span="12" class="left-panel" style="height: 100%;">
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
<h2>短期记忆区域</h2>
<div>
<el-button type="primary" @click="openSelectedDialog">查看已选单词</el-button>
<el-button type="success" @click="openDialog" style="margin-left: 10px;">选择单词</el-button>
</div>
</div>
<!-- 单词卡片 -->
<div class="card-container" v-if="reviewList.length">
<div class="card-wrapper">
<div class="card" :class="{ flipped: isFlipped }">
<div class="card-face card-front">
<h1>{{ currentWord.word }}</h1>
<el-button
@click.stop="speakWord(currentWord.word)"
style="background-color: #ffffff; border-color: #ffffff; color: #000000; margin-top: 20px;"
>
🔊 发音
</el-button>
</div>
<div class="card-face card-back">
<h1>{{ currentWord.word }}</h1>
<p><strong>释义:</strong>{{ currentWord.definition }}</p>
<p><strong>发音:</strong>{{ currentWord.pronunciation || '暂无' }}</p>
<el-button
@click.stop="speakWord(currentWord.word)"
style="background-color: #ffffff; border-color: #ffffff; color: #000000; margin-top: 20px;"
>
🔊 发音
</el-button>
</div>
</div>
<div class="btn-group">
<!-- 正面按钮,点击只翻转,不传数据 -->
<el-button
type="danger"
v-if="!isFlipped"
@click="flipCard"
>忘记</el-button>
<el-button
type="success"
v-if="!isFlipped"
@click="flipCard"
>认识</el-button>
<!-- 背面按钮,点击提交复习结果 -->
<el-button
type="danger"
v-if="isFlipped"
@click="submitReviewResult(false)"
>忘记</el-button>
<el-button
type="success"
v-if="isFlipped"
@click="submitReviewResult(true)"
>认识</el-button>
</div>
</div>
</div>
<!-- 已选单词弹窗 -->
<el-dialog v-model="selectedDialogVisible" title="已选单词列表" width="800px">
<el-table :data="selectedWords" style="width: 100%;" border @selection-change="handleSelectedChange">
<el-table-column type="selection" width="55" />
<el-table-column prop="id" label="ID" width="80" />
<el-table-column prop="word" label="单词" />
<el-table-column prop="definition" label="释义" />
<el-table-column label="操作" width="100">
<template #default="scope">
<el-button type="danger" size="small" @click="removeWord(scope.row)">删除</el-button>
</template>
</el-table-column>
</el-table>
<template #footer>
<span class="dialog-footer">
<el-button @click="selectedDialogVisible = false">关闭</el-button>
<el-button type="danger" :disabled="!selectedToDelete.length" @click="batchRemoveWords">
批量删除({{ selectedToDelete.length }})
</el-button>
</span>
</template>
</el-dialog>
</el-col>
<!-- 右侧:区域 -->
<el-col :span="12" class="right-panel" style="border: 1px solid #eee; padding: 20px;">
<h2>暂未开发</h2>
<p>暂未开发</p>
</el-col>
<!-- 弹窗:选择待学习单词 -->
<el-dialog v-model="dialogVisible" title="选择待学习单词" width="600px">
<el-table :data="pendingWords" style="width: 100%;" @selection-change="handleSelectionChange">
<el-table-column type="selection" width="55" />
<el-table-column prop="word" label="单词" />
<el-table-column prop="definition" label="释义" />
</el-table>
<template #footer>
<span class="dialog-footer">
<el-button @click="dialogVisible = false">取消</el-button>
<el-button type="primary" @click="submitSelectedWords">
确认选择({{ selectedToAdd.length }})
</el-button>
</span>
</template>
</el-dialog>
</el-row>
</template>
<script setup>
import { ref, computed, onMounted } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'
axios.defaults.baseURL = 'http://localhost:8080'
// 状态
const selectedWords = ref([])
const pendingWords = ref([])
const selectedToAdd = ref([])
const selectedToDelete = ref([])
const dialogVisible = ref(false)
const selectedDialogVisible = ref(false)
// 当前复习轮次
const round = ref(1)
// 复习单词列表(短期记忆复习单词,每轮调用接口获取)
const reviewList = ref([])
// 当前复习索引
const reviewIndex = ref(0)
// 卡片是否翻转状态
const isFlipped = ref(false)
// 当前复习单词
const currentWord = computed(() => {
return reviewList.value[reviewIndex.value] || {}
})
// 语音合成器缓存
const utterance = new SpeechSynthesisUtterance()
utterance.lang = 'en-US'
// 页面加载时预热语音合成器,减少首次朗读延迟
onMounted(() => {
speechSynthesis.speak(new SpeechSynthesisUtterance(' '))
fetchReviewList()
})
// 获取已选单词(用于已选单词弹窗)
const fetchSelectedWords = async () => {
const userId = localStorage.getItem('userId')
if (!userId) return ElMessage.warning("请先登录或设置 userId")
try {
const res = await axios.get('/study/select-words', { params: { userId } })
selectedWords.value = res.data
} catch {
ElMessage.error("获取已选单词失败")
}
}
// 获取当前轮复习列表(短期记忆,符合冷却原则+优先级)
const fetchReviewList = async () => {
const userId = localStorage.getItem('userId')
if (!userId) return ElMessage.warning("请先登录或设置 userId")
try {
const res = await axios.get('/study/review-list', {
params: { userId: Number(userId), round: round.value }
})
reviewList.value = res.data
reviewIndex.value = 0
isFlipped.value = false
if (reviewList.value.length === 0) {
ElMessage.success(`第${round.value}轮复习结束,无更多单词`)
return
}
speakWord(currentWord.value.word)
} catch (e) {
ElMessage.error("加载复习单词失败")
console.error(e)
}
}
// 翻转卡片(正面点击“忘记”或“认识”调用)
const flipCard = () => {
if (!currentWord.value.word) return
speakWord(currentWord.value.word)
isFlipped.value = true
}
// 提交复习结果(背面点击“忘记”或“认识”调用)
const submitReviewResult = async (remembered) => {
const userId = localStorage.getItem('userId')
if (!userId) {
ElMessage.warning("请先登录或设置 userId")
return
}
try {
await axios.post('/study/review-result', {
userId: Number(userId),
wordId: currentWord.value.wordId || currentWord.value.id,
round: round.value,
remembered: remembered
})
reviewIndex.value++
isFlipped.value = false
if (reviewIndex.value >= reviewList.value.length) {
round.value++
await fetchReviewList()
}
if (reviewIndex.value < reviewList.value.length) {
speakWord(currentWord.value.word)
}
} catch (e) {
ElMessage.error("提交复习结果失败")
console.error(e)
}
}
// 语音朗读函数
const speakWord = (text) => {
if (!text) return
if (speechSynthesis.speaking) {
speechSynthesis.cancel()
}
utterance.text = text
speechSynthesis.speak(utterance)
}
// 查看已选单词弹窗
const openSelectedDialog = async () => {
await fetchSelectedWords()
selectedToDelete.value = []
selectedDialogVisible.value = true
}
// 打开选择单词弹窗
const openDialog = async () => {
const userId = localStorage.getItem('userId')
if (!userId) return ElMessage.warning("请先登录或设置 userId")
try {
const res = await axios.get('/study/pending-words', {
params: { userId, limit: 100 }
})
pendingWords.value = res.data
dialogVisible.value = true
} catch {
ElMessage.error("获取待学习单词失败")
}
}
// 选择表格单词
const handleSelectionChange = (val) => {
selectedToAdd.value = val
}
const handleSelectedChange = (val) => {
selectedToDelete.value = val
}
// 确认添加单词
const submitSelectedWords = async () => {
const userId = localStorage.getItem('userId')
const wordIds = selectedToAdd.value.map(item => item.wordId || item.id)
if (wordIds.length < 10) return ElMessage.warning("请至少选择10个单词")
try {
await axios.post('/study/select-words', { userId: Number(userId), wordIds })
dialogVisible.value = false
await fetchSelectedWords()
ElMessage.success("添加成功")
} catch {
ElMessage.error("添加单词失败")
}
}
// 单个删除
const removeWord = async (row) => {
const userId = localStorage.getItem('userId')
try {
await axios.post('/study/remove-word', {
userId: Number(userId),
wordId: row.wordId || row.id
})
await fetchSelectedWords()
ElMessage.success("删除成功")
} catch {
ElMessage.error("删除失败")
}
}
// 批量删除
const batchRemoveWords = async () => {
const userId = localStorage.getItem('userId')
const wordIds = selectedToDelete.value.map(item => item.wordId || item.id)
if (!wordIds.length) return ElMessage.warning("请选择要删除的单词")
try {
await axios.post('/study/remove-words', { userId: Number(userId), wordIds })
await fetchSelectedWords()
selectedToDelete.value = []
ElMessage.success("批量删除成功")
} catch {
ElMessage.error("批量删除失败")
}
}
</script>
<style scoped>
.left-panel {
display: flex;
flex-direction: column;
border: 1px solid #eee;
height: 100%;
}
.card-container {
flex-grow: 1;
margin-top: 0;
display: flex;
flex-direction: column;
align-items: center;
justify-content: flex-start;
perspective: 1000px;
width: 100%;
}
/* 卡片尺寸你可以自己调整 */
.card {
width: 100%;
max-width: 550px;
height: 500px; /* ← 你可以根据需要自行改这个高度 */
position: relative;
transition: transform 0.6s;
transform-style: preserve-3d;
border-radius: 16px;
box-shadow: 0 8px 20px rgba(0, 0, 0, 0.15);
background-color: #fff;
}
.card.flipped {
transform: rotateY(180deg);
}
.card-face {
position: absolute;
width: 100%;
height: 100%;
padding: 20px;
box-sizing: border-box;
backface-visibility: hidden;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
.card-front {
font-size: 1em;
font-weight: bold;
}
.card-back {
transform: rotateY(180deg);
font-size: 1.2em;
text-align: center;
line-height: 1.6;
}
.card-wrapper {
display: flex;
flex-direction: column;
align-items: center;
}
.btn-group {
display: flex;
justify-content: center;
flex-wrap: wrap;
gap: 30px;
margin-top: 30px;
}
/* 按钮样式更大更显眼 */
.btn-group .el-button {
padding: 18px 40px;
font-size: 18px;
border-radius: 10px;
font-weight: bold;
min-width: 140px;
transition: all 0.2s ease-in-out;
}
.btn-group .el-button:hover {
transform: scale(1.05);
}
</style>
<!-- 左侧:学习单词区域 -->
<el-col :span="12" class="left-panel" style="height: 100%;">
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
<h2>短期记忆区域</h2>
<div>
<el-button type="primary" @click="openSelectedDialog">查看已选单词</el-button>
<el-button type="success" @click="openDialog" style="margin-left: 10px;">选择单词</el-button>
</div>
</div>
<!-- 单词卡片 -->
<div class="card-container" v-if="reviewList.length">
<div class="card-wrapper">
<div class="card" :class="{ flipped: isFlipped }">
<div class="card-face card-front">
<h1>{{ currentWord.word }}</h1>
<el-button
@click.stop="speakWord(currentWord.word)"
style="background-color: #ffffff; border-color: #ffffff; color: #000000; margin-top: 20px;"
>
🔊 发音
</el-button>
</div>
<div class="card-face card-back">
<h1>{{ currentWord.word }}</h1>
<p><strong>释义:</strong>{{ currentWord.definition }}</p>
<p><strong>发音:</strong>{{ currentWord.pronunciation || '暂无' }}</p>
<el-button
@click.stop="speakWord(currentWord.word)"
style="background-color: #ffffff; border-color: #ffffff; color: #000000; margin-top: 20px;"
>
🔊 发音
</el-button>
</div>
</div>
<div class="btn-group">
<!-- 正面按钮,点击只翻转,不传数据 -->
<el-button
type="danger"
v-if="!isFlipped"
@click="flipCard"
>忘记</el-button>
<el-button
type="success"
v-if="!isFlipped"
@click="flipCard"
>认识</el-button>
<!-- 背面按钮,点击提交复习结果 -->
<el-button
type="danger"
v-if="isFlipped"
@click="submitReviewResult(false)"
>忘记</el-button>
<el-button
type="success"
v-if="isFlipped"
@click="submitReviewResult(true)"
>认识</el-button>
</div>
</div>
</div>
<!-- 已选单词弹窗 -->
<el-dialog v-model="selectedDialogVisible" title="已选单词列表" width="800px">
<el-table :data="selectedWords" style="width: 100%;" border @selection-change="handleSelectedChange">
<el-table-column type="selection" width="55" />
<el-table-column prop="id" label="ID" width="80" />
<el-table-column prop="word" label="单词" />
<el-table-column prop="definition" label="释义" />
<el-table-column label="操作" width="100">
<template #default="scope">
<el-button type="danger" size="small" @click="removeWord(scope.row)">删除</el-button>
</template>
</el-table-column>
</el-table>
<template #footer>
<span class="dialog-footer">
<el-button @click="selectedDialogVisible = false">关闭</el-button>
<el-button type="danger" :disabled="!selectedToDelete.length" @click="batchRemoveWords">
批量删除({{ selectedToDelete.length }})
</el-button>
</span>
</template>
</el-dialog>
</el-col>
<!-- 右侧:区域 -->
<el-col :span="12" class="right-panel" style="border: 1px solid #eee; padding: 20px;">
<h2>暂未开发</h2>
<p>暂未开发</p>
</el-col>
<!-- 弹窗:选择待学习单词 -->
<el-dialog v-model="dialogVisible" title="选择待学习单词" width="600px">
<el-table :data="pendingWords" style="width: 100%;" @selection-change="handleSelectionChange">
<el-table-column type="selection" width="55" />
<el-table-column prop="word" label="单词" />
<el-table-column prop="definition" label="释义" />
</el-table>
<template #footer>
<span class="dialog-footer">
<el-button @click="dialogVisible = false">取消</el-button>
<el-button type="primary" @click="submitSelectedWords">
确认选择({{ selectedToAdd.length }})
</el-button>
</span>
</template>
</el-dialog>
初始化阶段
加载词库,为每个单词设置初始值:
score=0(分数,衡量熟练度),last_seen=-1(最后复习轮数,-1 表示未复习)。
全局参数:
cooldown=2(冷却轮数,复习后需间隔至少 2 轮才会再次出现)
pass_score=3(掌握阈值,分数≥3 时标记为 “已掌握”)
N=3(每轮复习前 N 个单词,可动态调整)
主循环逻辑(轮次迭代)
筛选冷却单词:
条件:当前轮数(round) - 单词.last_seen ≥ cooldown
含义:确保单词距离上一次复习已过足够轮数,避免频繁重复。
排序规则:
一级优先级:按score升序(低分优先,薄弱单词优先复习)。
二级优先级:若分数相同,按last_seen升序(冷却时间越久越优先)。
复习处理:
选取排序后的前 N 个单词,逐个展示并获取用户回答。
认识:score+1,若score≥pass_score则将已掌握单词放入“长期复习表”,每隔若干轮重新抽查;否则保留,记录last_seen=当前轮数。
忘记:score-1,记录last_seen=当前轮数,冷却结束后因低分优先复习。
终止条件:
当复习列表(review_list)为空时,流程结束。
上面的代码可以前后端互联,实现这个算法吗
Integer userId = Integer.valueOf(userIdStr);
return ResponseEntity.ok(studyService.getSelectedWordsByUserId(userId));
}
// 获取用户可选的未学习单词(用于前端弹窗选择)
@GetMapping("/pending-words")
public ResponseEntity<?> getPendingWords(
@RequestParam("userId") Integer userId,
@RequestParam(value = "limit", defaultValue = "100") Integer limit) {
return ResponseEntity.ok(studyService.getPendingWords(userId, limit));
}
// 删除用户选择的单词
@PostMapping("/remove-word")
public ResponseEntity<?> removeWord(@RequestBody Map<String, Object> payload) {
Integer userId = (Integer) payload.get("userId");
Integer wordId = (Integer) payload.get("wordId");
if (userId == null || wordId == null) {
return ResponseEntity.badRequest().body("参数错误");
}
int rows = studyService.deleteWord(userId, wordId);
if (rows > 0) {
return ResponseEntity.ok("删除成功");
} else {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body("未找到单词");
}
}
// 批量删除用户选择的单词
@PostMapping("/remove-words")
public ResponseEntity<?> removeWords(@RequestBody Map<String, Object> payload) {
Integer userId = (Integer) payload.get("userId");
List<Integer> wordIds = (List<Integer>) payload.get("wordIds");
if (userId == null || wordIds == null || wordIds.isEmpty()) {
return ResponseEntity.badRequest().body("参数错误");
}
int rows = studyService.deleteWords(userId, wordIds);
if (rows > 0) {
return ResponseEntity.ok("批量删除成功");
} else {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body("未找到单词");
}
}
// 获取当前轮复习列表
@GetMapping("/review-list")
public ResponseEntity<?> getReviewList(@RequestParam Integer userId, @RequestParam Integer round) {
List<Study> reviewList = studyService.getReviewList(userId, round);
return ResponseEntity.ok(reviewList);
}
// 处理复习结果
@PostMapping("/review-result")
public ResponseEntity<?> postReviewResult(@RequestBody Map<String, Object> payload) {
Integer userId = (Integer) payload.get("userId");
Integer wordId = (Integer) payload.get("wordId");
Integer round = (Integer) payload.get("round");
Boolean remembered = (Boolean) payload.get("remembered");
if (userId == null || wordId == null || round == null || remembered == null) {
return ResponseEntity.badRequest().body("参数错误");
}
studyService.processReviewResult(userId, wordId, round, remembered);
return ResponseEntity.ok("复习结果处理成功");
}
}
package com.example.springboot.service;
import com.example.springboot.entity.LongTermMemory;
import com.example.springboot.entity.Study;
import com.example.springboot.entity.Word;
import com.example.springboot.mapper.LongTermMemoryMapper;
import com.example.springboot.mapper.StudyMapper;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
@Service
public class StudyService {
code Copy code
@Resource
private StudyMapper studyMapper;
@Resource
private LongTermMemoryMapper longTermMemoryMapper;
private static final int COOLDOWN = 2;
private static final int PASS_SCORE = 3;
private static final int N = 3;
/**
* 获取当前轮次可复习单词列表(冷却结束且优先级最高的N个)
* @param userId 用户ID
* @param round 当前轮次
* @return 待复习单词列表
*/
public List<Study> getReviewList(Integer userId, int round) {
// 筛选 user_word_memory表中满足冷却条件的单词并排序,取前N个
return studyMapper.selectReviewCandidates(userId, round, COOLDOWN, N);
}
/**
* 处理用户对单词的复习反馈
* @param userId 用户ID
* @param wordId 单词ID
* @param currentRound 当前轮次
* @param remembered 是否记住(true表示认识,false表示忘记)
*/
public void processReviewResult(Integer userId, Integer wordId, int currentRound, boolean remembered) {
Study study = studyMapper.selectStudyByUserIdAndWordId(userId, wordId);
if (study == null) return;
int newScore = study.getScore();
if (remembered) {
newScore += 1;
} else {
newScore = Math.max(newScore - 1, 0);
}
if (newScore >= PASS_SCORE) {
// 达标,迁移到 long_term_memory
moveToLongTermMemory(study, currentRound, newScore);
studyMapper.deleteStudyByUserIdAndWordId(userId, wordId);
} else {
// 未达标,更新score及last_seen,留在 user_word_memory
study.setScore(newScore);
study.setLastSeen(currentRound);
studyMapper.updateStudy(study);
}
}
/**
* 新单词迁移到长期记忆表,初始各字段赋值
*/
private void moveToLongTermMemory(Study study, int currentRound, int score) {
// 创建 long_term_memory 实例(假设有相应实体类LongTermMemory)
LongTermMemory ltm = new LongTermMemory();
ltm.setUserId(study.getUserId());
ltm.setWordId(study.getWordId());
ltm.setReviewCount(1);
ltm.setEaseFactor(2.5f);
ltm.setIntervalDays(0);
ltm.setLastReviewDate(java.sql.Date.valueOf(java.time.LocalDate.now())); // 设置为当天
ltm.setNextReviewDate(java.sql.Date.valueOf(java.time.LocalDate.now().plusDays(1))); // 初始下一天复习
ltm.setLastScore(score);
longTermMemoryMapper.insertLongTermMemory(ltm);
}
// 用户手动选择单词加入记忆
public int insertUserSelectedWords(Integer userId, List<Integer> wordIds) {
int count = 0;
for (Integer wordId : wordIds) {
Study exist = studyMapper.selectStudyByUserIdAndWordId(userId, wordId);
if (exist == null) {
Study study = new Study();
study.setUserId(userId);
study.setWordId(wordId);
study.setScore(0);
study.setLastSeen(-1);
studyMapper.insertStudy(study);
count++;
}
}
return count;
}
// 获取用户选择的单词
public List<Word> getSelectedWordsByUserId(Integer userId) {
return studyMapper.selectSelectedWordsByUserId(userId);
}
// 获取待背单词
public List<Study> getPendingWords(Integer userId, int limit) {
return studyMapper.selectPendingWordsFromPlan(userId, limit);
}
// 删除单词
public int deleteWord(Integer userId, Integer wordId) {
return studyMapper.deleteStudyByUserIdAndWordId(userId, wordId);
}
// 批量删除
public int deleteWords(Integer userId, List<Integer> wordIds) {
return studyMapper.deleteStudiesByUserIdAndWordIds(userId, wordIds);
}
}
package com.example.springboot.mapper;
import com.example.springboot.entity.Study;
import com.example.springboot.entity.Word;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
@Mapper
public interface StudyMapper {
code Copy code
// 从user_word_plan抽取指定数量且user_word_memory中不存在的单词
List<Study> selectPendingWordsFromPlan(@Param("userId") Integer userId, @Param("limit") int limit);
// 查询 user_word_memory 中对应记录
Study selectStudyByUserIdAndWordId(@Param("userId") Integer userId, @Param("wordId") Integer wordId);
// 插入 user_word_memory
int insertStudy(Study study);
// 更新 user_word_memory
int updateStudy(Study study);
// 查询单词详情
Word selectWordById(@Param("id") Integer id);
// 查询某个用户的所有已选单词详细信息
List<Word> selectSelectedWordsByUserId(@Param("userId") Integer userId);
// 单个删除
int deleteStudyByUserIdAndWordId(@Param("userId") Integer userId, @Param("wordId") Integer wordId);
// 批量删除
int deleteStudiesByUserIdAndWordIds(@Param("userId") Integer userId, @Param("wordIds") List<Integer> wordIds);
// 根据冷却轮数筛选出符合条件的单词,排序返回前N个
List<Study> selectReviewCandidates(@Param("userId") Integer userId,
@Param("round") int round,
@Param("cooldown") int cooldown,
@Param("limit") int limit);
code Copy code
<!-- 从 user_word_plan 中抽取待学习且 user_word_memory 中不存在的单词 -->
<select id="selectPendingWordsFromPlan" parameterType="map" resultType="com.example.springboot.entity.Study">
SELECT
NULL AS id,
up.user_id AS userId,
up.word_id AS wordId,
w.word AS word,
w.definition AS definition,
0 AS score,
-1 AS lastSeen
FROM user_word_plan up
JOIN words w ON up.word_id = w.id
LEFT JOIN user_word_memory um ON up.user_id = um.user_id AND up.word_id = um.word_id
WHERE up.user_id = #{userId} AND up.status = 'pending' AND um.id IS NULL
ORDER BY up.added_at ASC
LIMIT #{limit}
</select>
<!-- 查询 user_word_memory -->
<select id="selectStudyByUserIdAndWordId" parameterType="map" resultType="com.example.springboot.entity.Study">
SELECT id, user_id AS userId, word_id AS wordId, score, last_seen AS lastSeen
FROM user_word_memory
WHERE user_id = #{userId} AND word_id = #{wordId}
</select>
<!-- 插入 user_word_memory -->
<insert id="insertStudy" parameterType="com.example.springboot.entity.Study" useGeneratedKeys="true" keyProperty="id">
INSERT INTO user_word_memory(user_id, word_id, score, last_seen)
VALUES(#{userId}, #{wordId}, #{score}, #{lastSeen})
</insert>
<!-- 更新 user_word_memory -->
<update id="updateStudy" parameterType="com.example.springboot.entity.Study">
UPDATE user_word_memory
SET score = #{score},
last_seen = #{lastSeen}
WHERE id = #{id}
</update>
<!-- 查询单词详情 -->
<select id="selectWordById" parameterType="int" resultType="com.example.springboot.entity.Word">
SELECT id, word, definition, pronunciation, custom_content AS customContent, created_at AS createdAt
FROM words
WHERE id = #{id}
</select>
<!-- 查询用户已选择的单词 -->
<select id="selectSelectedWordsByUserId" parameterType="int" resultType="com.example.springboot.entity.Word">
SELECT
w.id,
w.word,
w.definition,
w.pronunciation,
w.custom_content AS customContent,
w.created_at AS createdAt
FROM user_word_memory uwm
JOIN words w ON uwm.word_id = w.id
WHERE uwm.user_id = #{userId}
</select>
<!-- 删除单个单词 -->
<delete id="deleteStudyByUserIdAndWordId" parameterType="map">
DELETE FROM user_word_memory WHERE user_id = #{userId} AND word_id = #{wordId}
</delete>
<!-- 批量删除单词 -->
<delete id="deleteStudiesByUserIdAndWordIds" parameterType="map">
DELETE FROM user_word_memory WHERE user_id = #{userId} AND word_id IN
<foreach item="wordId" collection="wordIds" open="(" separator="," close=")">
#{wordId}
</foreach>
</delete>
<select id="selectReviewCandidates" resultType="com.example.springboot.entity.Study" parameterType="map">
SELECT id, user_id AS userId, word_id AS wordId, score, last_seen AS lastSeen
FROM user_word_memory
WHERE user_id = #{userId} AND #{round} - last_seen >= #{cooldown}
ORDER BY score ASC, last_seen ASC
LIMIT #{limit}
</select>
import com.example.springboot.entity.LongTermMemory;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface LongTermMemoryMapper {
int insertLongTermMemory(LongTermMemory ltm);
}
code Copy code
<!-- 左侧:学习单词区域 -->
<el-col :span="12" class="left-panel" style="height: 100%;">
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
<h2>短期记忆区域</h2>
<div>
<el-button type="primary" @click="openSelectedDialog">查看已选单词</el-button>
<el-button type="success" @click="openDialog" style="margin-left: 10px;">选择单词</el-button>
</div>
</div>
<!-- 单词卡片 -->
<div class="card-container" v-if="reviewList.length">
<div class="card-wrapper">
<div class="card" :class="{ flipped: isFlipped }">
<div class="card-face card-front">
<h1>{{ currentWord.word }}</h1>
<el-button
@click.stop="speakWord(currentWord.word)"
style="background-color: #ffffff; border-color: #ffffff; color: #000000; margin-top: 20px;"
>
🔊 发音
</el-button>
</div>
<div class="card-face card-back">
<h1>{{ currentWord.word }}</h1>
<p><strong>释义:</strong>{{ currentWord.definition }}</p>
<p><strong>发音:</strong>{{ currentWord.pronunciation || '暂无' }}</p>
<el-button
@click.stop="speakWord(currentWord.word)"
style="background-color: #ffffff; border-color: #ffffff; color: #000000; margin-top: 20px;"
>
🔊 发音
</el-button>
</div>
</div>
<div class="btn-group">
<!-- 正面按钮,点击只翻转,不传数据 -->
<el-button
type="danger"
v-if="!isFlipped"
@click="flipCard"
>忘记</el-button>
<el-button
type="success"
v-if="!isFlipped"
@click="flipCard"
>认识</el-button>
<!-- 背面按钮,点击提交复习结果 -->
<el-button
type="danger"
v-if="isFlipped"
@click="submitReviewResult(false)"
>忘记</el-button>
<el-button
type="success"
v-if="isFlipped"
@click="submitReviewResult(true)"
>认识</el-button>
</div>
</div>
</div>
<!-- 已选单词弹窗 -->
<el-dialog v-model="selectedDialogVisible" title="已选单词列表" width="800px">
<el-table :data="selectedWords" style="width: 100%;" border @selection-change="handleSelectedChange">
<el-table-column type="selection" width="55" />
<el-table-column prop="id" label="ID" width="80" />
<el-table-column prop="word" label="单词" />
<el-table-column prop="definition" label="释义" />
<el-table-column label="操作" width="100">
<template #default="scope">
<el-button type="danger" size="small" @click="removeWord(scope.row)">删除</el-button>
</template>
</el-table-column>
</el-table>
<template #footer>
<span class="dialog-footer">
<el-button @click="selectedDialogVisible = false">关闭</el-button>
<el-button type="danger" :disabled="!selectedToDelete.length" @click="batchRemoveWords">
批量删除({{ selectedToDelete.length }})
</el-button>
</span>
</template>
</el-dialog>
</el-col>
<!-- 右侧:区域 -->
<el-col :span="12" class="right-panel" style="border: 1px solid #eee; padding: 20px;">
<h2>暂未开发</h2>
<p>暂未开发</p>
</el-col>
<!-- 弹窗:选择待学习单词 -->
<el-dialog v-model="dialogVisible" title="选择待学习单词" width="600px">
<el-table :data="pendingWords" style="width: 100%;" @selection-change="handleSelectionChange">
<el-table-column type="selection" width="55" />
<el-table-column prop="word" label="单词" />
<el-table-column prop="definition" label="释义" />
</el-table>
<template #footer>
<span class="dialog-footer">
<el-button @click="dialogVisible = false">取消</el-button>
<el-button type="primary" @click="submitSelectedWords">
确认选择({{ selectedToAdd.length }})
</el-button>
</span>
</template>
</el-dialog>
SELECT
um.id,
um.user_id AS userId,
um.word_id AS wordId,
um.score,
um.last_seen AS lastSeen,
w.word,
w.definition,
w.pronunciation
FROM user_word_memory um
JOIN words w ON um.word_id = w.id
WHERE um.user_id = #{userId} AND #{round} - um.last_seen >= #{cooldown}
ORDER BY um.score ASC, um.last_seen ASC
LIMIT #{limit}
修改StudyMapper.xml里的selectReviewCandidates对应的SQL,确保返回 word、definition等。
2. 点击按钮无反应
纠正后的核心逻辑示例 (简化版,基于reviewList和reviewIndex) js Copy code
const flipCard = () => {
if (!currentWord.value.word) return
speakWord(currentWord.value.word)
isFlipped.value = true
}
const submitReviewResult = async (remembered) => {
const userId = localStorage.getItem('userId')
if (!userId) { ElMessage.warning("请先登录或设置 userId"); return }
try {
await axios.post('/study/review-result', {
userId: Number(userId),
wordId: currentWord.value.wordId || currentWord.value.id,
round: round.value,
remembered
})
reviewIndex.value++
isFlipped.value = false
if (reviewIndex.value >= reviewList.value.length) {
round.value++
await fetchReviewList()
} else {
speakWord(currentWord.value.word)
}
} catch (e) {
ElMessage.error("提交复习结果失败")
}
}
vue Copy code
<el-button v-if="!isFlipped" type="danger" @click="flipCard">忘记</el-button>
<el-button v-if="!isFlipped" type="success" @click="flipCard">认识</el-button>
<el-button v-if="isFlipped" type="danger" @click="submitReviewResult(false)">忘记</el-button>
<el-button v-if="isFlipped" type="success" @click="submitReviewResult(true)">认识</el-button>
总结
首要修正点 :完善后端selectReviewCandidates SQL,返回单词详情,包括word、definition等,保证前端 reviewList 有数据展示。
按钮事件逻辑调整 :根据reviewList的索引控制复习流程,不使用selectedWords。
保证后端及前端接口参数类型和字段一致 。
如果你需要,我可以帮你写修改后的完整 StudyMapper.xml 的selectReviewCandidates SQL,和修改后的 Vue 交互示例。需要吗?
<template>
<div class="card-container" v-if="reviewList.length">
<div class="card-wrapper">
<div class="card" :class="{ flipped: isFlipped }">
<!-- 卡片正面 -->
<div class="card-face card-front">
<h1>{{ currentWord.word }}</h1>
<el-button @click.stop="speakWord(currentWord.word)" style="background:#fff;border:none;color:#000;margin-top:20px;">
🔊 发音
</el-button>
</div>
<!-- 卡片背面 -->
<div class="card-face card-back">
<h1>{{ currentWord.word }}</h1>
<p><strong>释义:</strong>{{ currentWord.definition }}</p>
<p><strong>发音:</strong>{{ currentWord.pronunciation || '暂无' }}</p>
<el-button @click.stop="speakWord(currentWord.word)" style="background:#fff;border:none;color:#000;margin-top:20px;">
🔊 发音
</el-button>
</div>
</div>
<div class="btn-group">
<!-- 正面点击只翻转 -->
<el-button v-if="!isFlipped" type="danger" @click="flipCard">忘记</el-button>
<el-button v-if="!isFlipped" type="success" @click="flipCard">认识</el-button>
<!-- 背面点击提交结果 -->
<el-button v-if="isFlipped" type="danger" @click="submitReviewResult(false)">忘记</el-button>
<el-button v-if="isFlipped" type="success" @click="submitReviewResult(true)">认识</el-button>
</div>
</div>
</div>
<div v-else>
<p>无可复习单词,复习完成!</p>
</div>
</template>
<script setup>
import { ref, computed, onMounted } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'
axios.defaults.baseURL = 'http://localhost:8080'
const round = ref(1)
const reviewList = ref([])
const reviewIndex = ref(0)
const isFlipped = ref(false)
const utterance = new SpeechSynthesisUtterance()
utterance.lang = 'en-US'
const currentWord = computed(() => reviewList.value[reviewIndex.value] || {})
const speakWord = (text) => {
if (!text) return
if (speechSynthesis.speaking) speechSynthesis.cancel()
utterance.text = text
speechSynthesis.speak(utterance)
}
const fetchReviewList = async () => {
const userId = localStorage.getItem('userId')
if (!userId) {
ElMessage.warning('请先登录或设置 userId')
return
}
try {
const res = await axios.get('/study/review-list', {
params: { userId: Number(userId), round: round.value }
})
reviewList.value = res.data
reviewIndex.value = 0
isFlipped.value = false
if (reviewList.value.length > 0) {
speakWord(currentWord.value.word)
} else {
ElMessage.success(`第${round.value}轮复习结束,无更多单词!`)
}
} catch (error) {
ElMessage.error('获取复习单词失败')
console.error(error)
}
}
const flipCard = () => {
if (!currentWord.value.word) return
speakWord(currentWord.value.word)
isFlipped.value = true
}
const submitReviewResult = async (remembered) => {
const userId = localStorage.getItem('userId')
if (!userId) {
ElMessage.warning('请先登录或设置 userId')
return
}
try {
await axios.post('/study/review-result', {
userId: Number(userId),
wordId: currentWord.value.wordId || currentWord.value.id,
round: round.value,
remembered
})
reviewIndex.value++
isFlipped.value = false
if (reviewIndex.value >= reviewList.value.length) {
round.value++
await fetchReviewList()
} else {
speakWord(currentWord.value.word)
}
} catch (error) {
ElMessage.error('提交复习结果失败')
console.error(error)
}
}
onMounted(() => {
speechSynthesis.speak(new SpeechSynthesisUtterance(' ')) // 预热
fetchReviewList()
})
</script>
<style scoped>
/* 省略你的css,保持不变即可 */
</style>
总结:
修改后的 SQL 确保 selectReviewCandidates 返回完整单词数据,满足前端展示需求;
前端根据 reviewList 和 reviewIndex 渲染当前复习卡片,点击事件区分翻转和提交逻辑;
支持自动轮次递增和空列表提示。
如果需要,我还能帮你写详细的单元测试或者长期记忆复习逻辑。祝你开发顺利!
<!-- 左侧:学习单词区域 -->
<el-col :span="12" class="left-panel" style="height: 100%;">
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
<h2>短期记忆区域</h2>
<div>
<el-button type="primary" @click="openSelectedDialog">查看已选单词</el-button>
<el-button type="success" @click="openDialog" style="margin-left: 10px;">选择单词</el-button>
</div>
</div>
<!-- 单词卡片 -->
<div class="card-container" v-if="reviewList.length">
<div class="card-wrapper">
<div class="card" :class="{ flipped: isFlipped }">
<div class="card-face card-front">
<h1>{{ currentWord.word }}</h1>
<el-button
@click.stop="speakWord(currentWord.word)"
style="background-color: #ffffff; border-color: #ffffff; color: #000000; margin-top: 20px;"
>
🔊 发音
</el-button>
</div>
<div class="card-face card-back">
<h1>{{ currentWord.word }}</h1>
<p><strong>释义:</strong>{{ currentWord.definition }}</p>
<p><strong>发音:</strong>{{ currentWord.pronunciation || '暂无' }}</p>
<el-button
@click.stop="speakWord(currentWord.word)"
style="background-color: #ffffff; border-color: #ffffff; color: #000000; margin-top: 20px;"
>
🔊 发音
</el-button>
</div>
</div>
<div class="btn-group">
<!-- 正面按钮,点击只翻转,不传数据 -->
<el-button
type="danger"
v-if="!isFlipped"
@click="flipCard"
>忘记</el-button>
<el-button
type="success"
v-if="!isFlipped"
@click="flipCard"
>认识</el-button>
<!-- 背面按钮,点击提交复习结果 -->
<el-button
type="danger"
v-if="isFlipped"
@click="submitReviewResult(false)"
>忘记</el-button>
<el-button
type="success"
v-if="isFlipped"
@click="submitReviewResult(true)"
>认识</el-button>
</div>
</div>
</div>
<!-- 已选单词弹窗 -->
<el-dialog v-model="selectedDialogVisible" title="已选单词列表" width="800px">
<el-table :data="selectedWords" style="width: 100%;" border @selection-change="handleSelectedChange">
<el-table-column type="selection" width="55" />
<el-table-column prop="id" label="ID" width="80" />
<el-table-column prop="word" label="单词" />
<el-table-column prop="definition" label="释义" />
<el-table-column label="操作" width="100">
<template #default="scope">
<el-button type="danger" size="small" @click="removeWord(scope.row)">删除</el-button>
</template>
</el-table-column>
</el-table>
<template #footer>
<span class="dialog-footer">
<el-button @click="selectedDialogVisible = false">关闭</el-button>
<el-button type="danger" :disabled="!selectedToDelete.length" @click="batchRemoveWords">
批量删除({{ selectedToDelete.length }})
</el-button>
</span>
</template>
</el-dialog>
</el-col>
<!-- 右侧:区域 -->
<el-col :span="12" class="right-panel" style="border: 1px solid #eee; padding: 20px;">
<h2>暂未开发</h2>
<p>暂未开发</p>
</el-col>
<!-- 弹窗:选择待学习单词 -->
<el-dialog v-model="dialogVisible" title="选择待学习单词" width="600px">
<el-table :data="pendingWords" style="width: 100%;" @selection-change="handleSelectionChange">
<el-table-column type="selection" width="55" />
<el-table-column prop="word" label="单词" />
<el-table-column prop="definition" label="释义" />
</el-table>
<template #footer>
<span class="dialog-footer">
<el-button @click="dialogVisible = false">取消</el-button>
<el-button type="primary" @click="submitSelectedWords">
确认选择({{ selectedToAdd.length }})
</el-button>
</span>
</template>
</el-dialog>
<template>
<el-row style="height: 100vh; padding: 20px;" :gutter="20">
<!-- 左侧:学习单词区域 -->
<el-col :span="12" class="left-panel" style="height: 100%;">
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
<h2>短期记忆区域</h2>
<div>
<el-button type="primary" @click="openSelectedDialog">查看已选单词</el-button>
<el-button type="success" @click="openDialog" style="margin-left: 10px;">选择单词</el-button>
</div>
</div>
<!-- 单词卡片 -->
<div class="card-container" v-if="reviewList.length">
<div class="card-wrapper">
<div class="card" :class="{ flipped: isFlipped }">
<div class="card-face card-front">
<h1>{{ currentWord.word }}</h1>
<el-button
@click.stop="speakWord(currentWord.word)"
style="background-color: #ffffff; border-color: #ffffff; color: #000000; margin-top: 20px;"
>
🔊 发音
</el-button>
</div>
<div class="card-face card-back">
<h1>{{ currentWord.word }}</h1>
<p><strong>释义:</strong>{{ currentWord.definition }}</p>
<p><strong>发音:</strong>{{ currentWord.pronunciation || '暂无' }}</p>
<el-button
@click.stop="speakWord(currentWord.word)"
style="background-color: #ffffff; border-color: #ffffff; color: #000000; margin-top: 20px;"
>
🔊 发音
</el-button>
</div>
</div>
<div class="btn-group">
<!-- 正面按钮,点击只翻转,不传数据 -->
<el-button
type="danger"
v-if="!isFlipped"
@click="flipCard"
>忘记</el-button>
<el-button
type="success"
v-if="!isFlipped"
@click="flipCard"
>认识</el-button>
<!-- 背面按钮,点击提交复习结果 -->
<el-button
type="danger"
v-if="isFlipped"
@click="submitReviewResult(false)"
>忘记</el-button>
<el-button
type="success"
v-if="isFlipped"
@click="submitReviewResult(true)"
>认识</el-button>
</div>
</div>
</div>
<!-- 当没有复习单词时显示提示 -->
<div v-else style="text-align:center; margin-top: 50px; font-size: 20px; color: #999;">
无可复习单词,复习完成!
</div>
<!-- 已选单词弹窗 -->
<el-dialog v-model="selectedDialogVisible" title="已选单词列表" width="800px">
<el-table
:data="selectedWords"
style="width: 100%;"
border
@selection-change="handleSelectedChange"
>
<el-table-column type="selection" width="55" />
<el-table-column prop="id" label="ID" width="80" />
<el-table-column prop="word" label="单词" />
<el-table-column prop="definition" label="释义" />
<el-table-column label="操作" width="100">
<template #default="scope">
<el-button type="danger" size="small" @click="removeWord(scope.row)">删除</el-button>
</template>
</el-table-column>
</el-table>
<template #footer>
<span class="dialog-footer">
<el-button @click="selectedDialogVisible = false">关闭</el-button>
<el-button type="danger" :disabled="!selectedToDelete.length" @click="batchRemoveWords">
批量删除({{ selectedToDelete.length }})
</el-button>
</span>
</template>
</el-dialog>
</el-col>
<!-- 右侧:区域 -->
<el-col :span="12" class="right-panel" style="border: 1px solid #eee; padding: 20px;">
<h2>暂未开发</h2>
<p>暂未开发</p>
</el-col>
<!-- 弹窗:选择待学习单词 -->
<el-dialog v-model="dialogVisible" title="选择待学习单词" width="600px">
<el-table :data="pendingWords" style="width: 100%;" @selection-change="handleSelectionChange">
<el-table-column type="selection" width="55" />
<el-table-column prop="word" label="单词" />
<el-table-column prop="definition" label="释义" />
</el-table>
<template #footer>
<span class="dialog-footer">
<el-button @click="dialogVisible = false">取消</el-button>
<el-button type="primary" @click="submitSelectedWords">
确认选择({{ selectedToAdd.length }})
</el-button>
</span>
</template>
</el-dialog>
</el-row>
</template>
<script setup>
import { ref, computed, onMounted } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'
axios.defaults.baseURL = 'http://localhost:8080'
// 状态
const selectedWords = ref([])
const pendingWords = ref([])
const selectedToAdd = ref([])
const selectedToDelete = ref([])
const dialogVisible = ref(false)
const selectedDialogVisible = ref(false)
// 当前复习轮次
const round = ref(1)
// 复习单词列表(短期记忆复习单词,每轮调用接口获取)
const reviewList = ref([])
// 当前复习索引
const reviewIndex = ref(0)
// 卡片是否翻转状态
const isFlipped = ref(false)
// 当前复习单词
const currentWord = computed(() => {
return reviewList.value[reviewIndex.value] || {}
})
// 语音合成器缓存
const utterance = new SpeechSynthesisUtterance()
utterance.lang = 'en-US'
// 页面加载时预热语音合成器,减少首次朗读延迟
onMounted(() => {
speechSynthesis.speak(new SpeechSynthesisUtterance(' '))
fetchReviewList()
})
// 获取已选单词(用于已选单词弹窗)
const fetchSelectedWords = async () => {
const userId = localStorage.getItem('userId')
if (!userId) return ElMessage.warning("请先登录或设置 userId")
try {
const res = await axios.get('/study/select-words', { params: { userId } })
selectedWords.value = res.data
} catch {
ElMessage.error("获取已选单词失败")
}
}
// 获取当前轮复习列表(短期记忆,符合冷却原则+优先级)
const fetchReviewList = async () => {
const userId = localStorage.getItem('userId')
if (!userId) return ElMessage.warning("请先登录或设置 userId")
try {
const res = await axios.get('/study/review-list', {
params: { userId: Number(userId), round: round.value }
})
reviewList.value = res.data
reviewIndex.value = 0
isFlipped.value = false
if (reviewList.value.length === 0) {
ElMessage.success(`第${round.value}轮复习结束,无更多单词`)
return
}
speakWord(currentWord.value.word)
} catch (e) {
ElMessage.error("加载复习单词失败")
console.error(e)
}
}
// 翻转卡片(正面点击“忘记”或“认识”调用)
const flipCard = () => {
if (!currentWord.value.word) return
speakWord(currentWord.value.word)
isFlipped.value = true
}
// 提交复习结果(背面点击“忘记”或“认识”调用)
const submitReviewResult = async (remembered) => {
const userId = localStorage.getItem('userId')
if (!userId) {
ElMessage.warning("请先登录或设置 userId")
return
}
try {
await axios.post('/study/review-result', {
userId: Number(userId),
wordId: currentWord.value.wordId || currentWord.value.id,
round: round.value,
remembered: remembered
})
reviewIndex.value++
isFlipped.value = false
if (reviewIndex.value >= reviewList.value.length) {
round.value++
await fetchReviewList()
}
if (reviewIndex.value < reviewList.value.length) {
speakWord(currentWord.value.word)
}
} catch (e) {
ElMessage.error("提交复习结果失败")
console.error(e)
}
}
// 语音朗读函数
const speakWord = (text) => {
if (!text) return
if (speechSynthesis.speaking) {
speechSynthesis.cancel()
}
utterance.text = text
speechSynthesis.speak(utterance)
}
// 查看已选单词弹窗
const openSelectedDialog = async () => {
await fetchSelectedWords()
selectedToDelete.value = []
selectedDialogVisible.value = true
}
// 打开选择单词弹窗
const openDialog = async () => {
const userId = localStorage.getItem('userId')
if (!userId) return ElMessage.warning("请先登录或设置 userId")
try {
const res = await axios.get('/study/pending-words', {
params: { userId, limit: 100 }
})
pendingWords.value = res.data
dialogVisible.value = true
} catch {
ElMessage.error("获取待学习单词失败")
}
}
// 选择表格单词
const handleSelectionChange = (val) => {
selectedToAdd.value = val
}
const handleSelectedChange = (val) => {
selectedToDelete.value = val
}
// 确认添加单词
const submitSelectedWords = async () => {
const userId = localStorage.getItem('userId')
const wordIds = selectedToAdd.value.map(item => item.wordId || item.id)
if (wordIds.length < 10) return ElMessage.warning("请至少选择10个单词")
try {
await axios.post('/study/select-words', { userId: Number(userId), wordIds })
dialogVisible.value = false
await fetchSelectedWords()
ElMessage.success("添加成功")
} catch {
ElMessage.error("添加单词失败")
}
}
// 单个删除
const removeWord = async (row) => {
const userId = localStorage.getItem('userId')
try {
await axios.post('/study/remove-word', {
userId: Number(userId),
wordId: row.wordId || row.id
})
await fetchSelectedWords()
ElMessage.success("删除成功")
} catch {
ElMessage.error("删除失败")
}
}
// 批量删除
const batchRemoveWords = async () => {
const userId = localStorage.getItem('userId')
const wordIds = selectedToDelete.value.map(item => item.wordId || item.id)
if (!wordIds.length) return ElMessage.warning("请选择要删除的单词")
try {
await axios.post('/study/remove-words', { userId: Number(userId), wordIds })
await fetchSelectedWords()
selectedToDelete.value = []
ElMessage.success("批量删除成功")
} catch {
ElMessage.error("批量删除失败")
}
}
</script>
<style scoped>
.left-panel {
display: flex;
flex-direction: column;
border: 1px solid #eee;
height: 100%;
}
.card-container {
flex-grow: 1;
margin-top: 0;
display: flex;
flex-direction: column;
align-items: center;
justify-content: flex-start;
perspective: 1000px;
width: 100%;
}
/* 卡片尺寸你可以自己调整 */
.card {
width: 100%;
max-width: 550px;
height: 500px; /* ← 你可以根据需要自行改这个高度 */
position: relative;
transition: transform 0.6s;
transform-style: preserve-3d;
border-radius: 16px;
box-shadow: 0 8px 20px rgba(0, 0, 0, 0.15);
background-color: #fff;
}
.card.flipped {
transform: rotateY(180deg);
}
.card-face {
position: absolute;
width: 100%;
height: 100%;
padding: 20px;
box-sizing: border-box;
backface-visibility: hidden;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
.card-front {
font-size: 1em;
font-weight: bold;
}
.card-back {
transform: rotateY(180deg);
font-size: 1.2em;
text-align: center;
line-height: 1.6;
}
.card-wrapper {
display: flex;
flex-direction: column;
align-items: center;
}
.btn-group {
display: flex;
justify-content: center;
flex-wrap: wrap;
gap: 30px;
margin-top: 30px;
}
/* 按钮样式更大更显眼 */
.btn-group .el-button {
padding: 18px 40px;
font-size: 18px;
border-radius: 10px;
font-weight: bold;
min-width: 140px;
transition: all 0.2s ease-in-out;
}
.btn-group .el-button:hover {
transform: scale(1.05);
}
</style>
<!-- 左侧:学习单词区域 -->
<el-col :span="12" class="left-panel" style="height: 100%;">
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
<h2>短期记忆区域</h2>
<div>
<el-button type="primary" @click="openSelectedDialog">查看已选单词</el-button>
<el-button type="success" @click="openDialog" style="margin-left: 10px;">选择单词</el-button>
</div>
</div>
<!-- 单词卡片 -->
<div class="card-container" v-if="reviewList.length">
<div class="card-wrapper">
<div class="card" :class="{ flipped: isFlipped }">
<div class="card-face card-front">
<h1>{{ currentWord.word }}</h1>
<el-button
@click.stop="speakWord(currentWord.word)"
style="background-color: #ffffff; border-color: #ffffff; color: #000000; margin-top: 20px;"
>
🔊 发音
</el-button>
</div>
<div class="card-face card-back">
<h1>{{ currentWord.word }}</h1>
<p><strong>释义:</strong>{{ currentWord.definition }}</p>
<el-button
@click.stop="speakWord(currentWord.word)"
style="background-color: #ffffff; border-color: #ffffff; color: #000000; margin-top: 20px;"
>
🔊 发音
</el-button>
</div>
</div>
<div class="btn-group">
<!-- 正面按钮,点击只翻转,不传数据 -->
<el-button
type="danger"
v-if="!isFlipped"
@click="flipCard"
>忘记</el-button>
<el-button
type="success"
v-if="!isFlipped"
@click="flipCard"
>认识</el-button>
<!-- 背面按钮,点击提交复习结果 -->
<el-button
type="danger"
v-if="isFlipped"
@click="submitReviewResult(false)"
>忘记</el-button>
<el-button
type="success"
v-if="isFlipped"
@click="submitReviewResult(true)"
>认识</el-button>
</div>
</div>
</div>
<!-- 当没有复习单词时显示提示 -->
<div v-else style="text-align:center; margin-top: 50px; font-size: 20px; color: #999;">
无可复习单词,复习完成!
</div>
<!-- 已选单词弹窗 -->
<el-dialog v-model="selectedDialogVisible" title="已选单词列表" width="800px">
<el-table
:data="selectedWords"
style="width: 100%;"
border
@selection-change="handleSelectedChange"
>
<el-table-column type="selection" width="55" />
<el-table-column prop="id" label="ID" width="80" />
<el-table-column prop="word" label="单词" />
<el-table-column prop="definition" label="释义" />
<el-table-column label="操作" width="100">
<template #default="scope">
<el-button type="danger" size="small" @click="removeWord(scope.row)">删除</el-button>
</template>
</el-table-column>
</el-table>
<template #footer>
<span class="dialog-footer">
<el-button @click="selectedDialogVisible = false">关闭</el-button>
<el-button type="danger" :disabled="!selectedToDelete.length" @click="batchRemoveWords">
批量删除({{ selectedToDelete.length }})
</el-button>
</span>
</template>
</el-dialog>
</el-col>
<!-- 右侧:区域 -->
<el-col :span="12" class="right-panel" style="border: 1px solid #eee; padding: 20px;">
<h2>暂未开发</h2>
<p>暂未开发</p>
</el-col>
<!-- 弹窗:选择待学习单词 -->
<el-dialog v-model="dialogVisible" title="选择待学习单词" width="600px">
<el-table :data="pendingWords" style="width: 100%;" @selection-change="handleSelectionChange">
<el-table-column type="selection" width="55" />
<el-table-column prop="word" label="单词" />
<el-table-column prop="definition" label="释义" />
</el-table>
<template #footer>
<span class="dialog-footer">
<el-button @click="dialogVisible = false">取消</el-button>
<el-button type="primary" @click="submitSelectedWords">
确认选择({{ selectedToAdd.length }})
</el-button>
</span>
</template>
</el-dialog>
用户背面点击一次认识,左上角对应单词显示认识的次数,比如我现在已经点击2次了,左上角显示2/3,否则用户都不知道自己点击了多少次认识。注意卡片正面点击的认识不算
<template>
<el-row style="height: 100vh; padding: 20px;" :gutter="20">
<!-- ... 省略左侧其他代码 ... -->
<!-- 单词卡片 -->
<div class="card-container" v-if="reviewList.length">
<div class="card-wrapper">
<div class="card" :class="{ flipped: isFlipped }">
<div class="card-face card-front">
<div style="position: absolute; top: 8px; left: 10px; font-weight: bold; font-size: 14px; color: #999;">
{{ currentWord.rememberCount || 0 }}/3
</div>
<h1>{{ currentWord.word }}</h1>
<el-button
@click.stop="speakWord(currentWord.word)"
style="background-color: #ffffff; border-color: #ffffff; color: #000000; margin-top: 20px;"
>
🔊 发音
</el-button>
</div>
<div class="card-face card-back">
<h1>{{ currentWord.word }}</h1>
<p><strong>释义:</strong>{{ currentWord.definition }}</p>
<p><strong>发音:</strong>{{ currentWord.pronunciation || '暂无' }}</p>
<el-button
@click.stop="speakWord(currentWord.word)"
style="background-color: #ffffff; border-color: #ffffff; color: #000000; margin-top: 20px;"
>
🔊 发音
</el-button>
</div>
</div>
<div class="btn-group">
<!-- 正面按钮,点击只翻转,不传数据 -->
<el-button
type="danger"
v-if="!isFlipped"
@click="flipCard"
>忘记</el-button>
<el-button
type="success"
v-if="!isFlipped"
@click="flipCard"
>认识</el-button>
<!-- 背面按钮,点击提交复习结果 -->
<el-button
type="danger"
v-if="isFlipped"
@click="submitReviewResult(false)"
>忘记</el-button>
<el-button
type="success"
v-if="isFlipped"
@click="submitReviewResult(true)"
>认识</el-button>
</div>
</div>
</div>
<!-- ... 省略其余代码 ... -->
</el-row>
</template>
<script setup>
// ... 省略导入和变量声明部分 ...
// 修改 fetchReviewList ,初始化 rememberCount:
const fetchReviewList = async () => {
const userId = localStorage.getItem('userId')
if (!userId) return ElMessage.warning("请先登录或设置 userId")
try {
const res = await axios.get('/study/review-list', {
params: { userId: Number(userId), round: round.value }
})
reviewList.value = res.data.map(item => ({ ...item, rememberCount: 0 })) // 初始化计数为0
reviewIndex.value = 0
isFlipped.value = false
if (reviewList.value.length === 0) {
ElMessage.success(`第${round.value}轮复习结束,无更多单词`)
return
}
speakWord(currentWord.value.word)
} catch (e) {
ElMessage.error("加载复习单词失败")
console.error(e)
}
}
// 修改 submitReviewResult :背面认识时计数+1
const submitReviewResult = async (remembered) => {
const userId = localStorage.getItem('userId')
if (!userId) {
ElMessage.warning("请先登录或设置 userId")
return
}
try {
await axios.post('/study/review-result', {
userId: Number(userId),
wordId: currentWord.value.wordId || currentWord.value.id,
round: round.value,
remembered: remembered
})
if (remembered) {
// 只有认识按钮,记忆加1
reviewList.value[reviewIndex.value].rememberCount =
(reviewList.value[reviewIndex.value].rememberCount || 0) + 1
}
reviewIndex.value++
isFlipped.value = false
if (reviewIndex.value >= reviewList.value.length) {
round.value++
await fetchReviewList()
}
if (reviewIndex.value < reviewList.value.length) {
speakWord(currentWord.value.word)
}
} catch (e) {
ElMessage.error("提交复习结果失败")
console.error(e)
}
}
</script>
说明
rememberCount 只在前端维护,不影响后端数据
每传一个“认识”的背面结果,计数+1并展示
计数显示格式比如 2/3 中,3为固定的pass_score,可按需绑定变量
点击“忘记”不增加计数,也不减少计数,这样用户看到的次数是真实点击认识背面的次数
这样用户在复习背面点击“认识”时就能清晰看到自己的累计操作次数,提升学习反馈感。
需要我帮你写个完整带计数功能的示例或其它功能,随时跟我说。
<template>
<el-row style="height: 100vh; padding: 20px;" :gutter="20">
<!-- 左侧:学习单词区域 -->
<el-col :span="12" class="left-panel" style="height: 100%;">
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
<h2>短期记忆区域</h2>
<div>
<el-button type="primary" @click="openSelectedDialog">查看已选单词</el-button>
<el-button type="success" @click="openDialog" style="margin-left: 10px;">选择单词</el-button>
</div>
</div>
<!-- 单词卡片 -->
<div class="card-container" v-if="reviewList.length">
<div class="card-wrapper">
<div class="card" :class="{ flipped: isFlipped }">
<div class="card-face card-front">
<div style="position: absolute; top: 8px; left: 10px; font-weight: bold; font-size: 14px; color: #999;">
{{ currentWord.rememberCount || 0 }}/3
</div>
<h1>{{ currentWord.word }}</h1>
<el-button
@click.stop="speakWord(currentWord.word)"
style="background-color: #ffffff; border-color: #ffffff; color: #000000; margin-top: 20px;"
>
🔊 发音
</el-button>
</div>
<div class="card-face card-back">
<h1>{{ currentWord.word }}</h1>
<p><strong>释义:</strong>{{ currentWord.definition }}</p>
<p><strong>发音:</strong>{{ currentWord.pronunciation || '暂无' }}</p>
<el-button
@click.stop="speakWord(currentWord.word)"
style="background-color: #ffffff; border-color: #ffffff; color: #000000; margin-top: 20px;"
>
🔊 发音
</el-button>
</div>
</div>
<div class="btn-group">
<!-- 正面按钮,点击只翻转,不传数据 -->
<el-button type="danger" v-if="!isFlipped" @click="flipCard">忘记</el-button>
<el-button type="success" v-if="!isFlipped" @click="flipCard">认识</el-button>
<!-- 背面按钮,点击提交复习结果 -->
<el-button type="danger" v-if="isFlipped" @click="submitReviewResult(false)">忘记</el-button>
<el-button type="success" v-if="isFlipped" @click="submitReviewResult(true)">认识</el-button>
</div>
</div>
</div>
<!-- 当没有复习单词时显示提示 -->
<div v-else style="text-align:center; margin-top: 50px; font-size: 20px; color: #999;">
无可复习单词,复习完成!
</div>
<!-- 已选单词弹窗 -->
<el-dialog v-model="selectedDialogVisible" title="已选单词列表" width="800px">
<el-table
:data="selectedWords"
style="width: 100%;"
border
@selection-change="handleSelectedChange"
>
<el-table-column type="selection" width="55" />
<el-table-column prop="id" label="ID" width="80" />
<el-table-column prop="word" label="单词" />
<el-table-column prop="definition" label="释义" />
<el-table-column label="操作" width="100">
<template #default="scope">
<el-button type="danger" size="small" @click="removeWord(scope.row)">删除</el-button>
</template>
</el-table-column>
</el-table>
<template #footer>
<span class="dialog-footer">
<el-button @click="selectedDialogVisible = false">关闭</el-button>
<el-button type="danger" :disabled="!selectedToDelete.length" @click="batchRemoveWords">
批量删除({{ selectedToDelete.length }})
</el-button>
</span>
</template>
</el-dialog>
</el-col>
<!-- 右侧:区域 -->
<el-col :span="12" class="right-panel" style="border: 1px solid #eee; padding: 20px;">
<h2>暂未开发</h2>
<p>暂未开发</p>
</el-col>
<!-- 弹窗:选择待学习单词 -->
<el-dialog v-model="dialogVisible" title="选择待学习单词" width="600px">
<el-table :data="pendingWords" style="width: 100%;" @selection-change="handleSelectionChange">
<el-table-column type="selection" width="55" />
<el-table-column prop="word" label="单词" />
<el-table-column prop="definition" label="释义" />
</el-table>
<template #footer>
<span class="dialog-footer">
<el-button @click="dialogVisible = false">取消</el-button>
<el-button type="primary" @click="submitSelectedWords">
确认选择({{ selectedToAdd.length }})
</el-button>
</span>
</template>
</el-dialog>
</el-row>
</template>
<script setup>
import { ref, computed, onMounted } from "vue";
import axios from "axios";
import { ElMessage } from "element-plus";
axios.defaults.baseURL = "http://localhost:8080";
// 状态
const selectedWords = ref([]);
const pendingWords = ref([]);
const selectedToAdd = ref([]);
const selectedToDelete = ref([]);
const dialogVisible = ref(false);
const selectedDialogVisible = ref(false);
// 当前复习轮次
const round = ref(1);
// 复习单词列表(短期记忆复习单词,每轮调用接口获取)
const reviewList = ref([]);
// 当前复习索引
const reviewIndex = ref(0);
// 卡片是否翻转状态
const isFlipped = ref(false);
// 当前复习单词
const currentWord = computed(() => {
return reviewList.value[reviewIndex.value] || {};
});
// 语音合成器缓存
const utterance = new SpeechSynthesisUtterance();
utterance.lang = "en-US";
// 页面加载时预热语音合成器,减少首次朗读延迟
onMounted(() => {
speechSynthesis.speak(new SpeechSynthesisUtterance(" "));
fetchReviewList();
});
// 获取已选单词(用于已选单词弹窗)
const fetchSelectedWords = async () => {
const userId = localStorage.getItem("userId");
if (!userId) return ElMessage.warning("请先登录或设置 userId");
try {
const res = await axios.get("/study/select-words", { params: { userId } });
selectedWords.value = res.data;
} catch {
ElMessage.error("获取已选单词失败");
}
};
// 获取当前轮复习列表(短期记忆,符合冷却原则+优先级)
const fetchReviewList = async () => {
const userId = localStorage.getItem("userId");
if (!userId) return ElMessage.warning("请先登录或设置 userId");
try {
const res = await axios.get("/study/review-list", {
params: { userId: Number(userId), round: round.value }
});
// 初始化rememberCount为0
reviewList.value = res.data.map(item => ({
...item,
rememberCount: 0,
}));
reviewIndex.value = 0;
isFlipped.value = false;
if (reviewList.value.length === 0) {
ElMessage.success(`第${round.value}轮复习结束,无更多单词`);
return;
}
speakWord(currentWord.value.word);
} catch (e) {
ElMessage.error("加载复习单词失败");
console.error(e);
}
};
// 翻转卡片(正面点击“忘记”或“认识”调用)
const flipCard = () => {
if (!currentWord.value.word) return;
speakWord(currentWord.value.word);
isFlipped.value = true;
};
// 提交复习结果(背面点击“忘记”或“认识”调用)
const submitReviewResult = async (remembered) => {
const userId = localStorage.getItem("userId");
if (!userId) {
ElMessage.warning("请先登录或设置 userId");
return;
}
try {
await axios.post("/study/review-result", {
userId: Number(userId),
wordId: currentWord.value.wordId || currentWord.value.id,
round: round.value,
remembered: remembered,
});
if (remembered) {
// 认识时计数加1
reviewList.value[reviewIndex.value].rememberCount =
(reviewList.value[reviewIndex.value].rememberCount || 0) + 1;
} else {
// 忘记时计数减1,最小为0
reviewList.value[reviewIndex.value].rememberCount = Math.max(
(reviewList.value[reviewIndex.value].rememberCount || 0) - 1,
0
);
}
reviewIndex.value++;
isFlipped.value = false;
if (reviewIndex.value >= reviewList.value.length) {
round.value++;
await fetchReviewList();
} else {
speakWord(currentWord.value.word);
}
} catch (e) {
ElMessage.error("提交复习结果失败");
console.error(e);
}
};
// 语音朗读函数
const speakWord = (text) => {
if (!text) return;
if (speechSynthesis.speaking) {
speechSynthesis.cancel();
}
utterance.text = text;
speechSynthesis.speak(utterance);
};
// 查看已选单词弹窗
const openSelectedDialog = async () => {
await fetchSelectedWords();
selectedToDelete.value = [];
selectedDialogVisible.value = true;
};
// 打开选择单词弹窗
const openDialog = async () => {
const userId = localStorage.getItem("userId");
if (!userId) return ElMessage.warning("请先登录或设置 userId");
try {
const res = await axios.get("/study/pending-words", {
params: { userId, limit: 100 },
});
pendingWords.value = res.data;
dialogVisible.value = true;
} catch {
ElMessage.error("获取待学习单词失败");
}
};
// 选择表格单词
const handleSelectionChange = (val) => {
selectedToAdd.value = val;
};
const handleSelectedChange = (val) => {
selectedToDelete.value = val;
};
// 确认添加单词
const submitSelectedWords = async () => {
const userId = localStorage.getItem("userId");
const wordIds = selectedToAdd.value.map((item) => item.wordId || item.id);
if (wordIds.length < 10)
return ElMessage.warning("请至少选择10个单词");
try {
await axios.post("/study/select-words", { userId: Number(userId), wordIds });
dialogVisible.value = false;
await fetchSelectedWords();
ElMessage.success("添加成功");
} catch {
ElMessage.error("添加单词失败");
}
};
// 单个删除
const removeWord = async (row) => {
const userId = localStorage.getItem("userId");
try {
await axios.post("/study/remove-word", {
userId: Number(userId),
wordId: row.wordId || row.id,
});
await fetchSelectedWords();
ElMessage.success("删除成功");
} catch {
ElMessage.error("删除失败");
}
};
// 批量删除
const batchRemoveWords = async () => {
const userId = localStorage.getItem("userId");
const wordIds = selectedToDelete.value.map((item) => item.wordId || item.id);
if (!wordIds.length) return ElMessage.warning("请选择要删除的单词");
try {
await axios.post("/study/remove-words", { userId: Number(userId), wordIds });
await fetchSelectedWords();
selectedToDelete.value = [];
ElMessage.success("批量删除成功");
} catch {
ElMessage.error("批量删除失败");
}
};
</script>
<style scoped>
.left-panel {
display: flex;
flex-direction: column;
border: 1px solid #eee;
height: 100%;
}
.card-container {
flex-grow: 1;
margin-top: 0;
display: flex;
flex-direction: column;
align-items: center;
justify-content: flex-start;
perspective: 1000px;
width: 100%;
}
/* 卡片尺寸可自行调整 */
.card {
width: 100%;
max-width: 550px;
height: 500px; /* 可调整 */
position: relative;
transition: transform 0.6s;
transform-style: preserve-3d;
border-radius: 16px;
box-shadow: 0 8px 20px rgba(0, 0, 0, 0.15);
background-color: #fff;
}
.card.flipped {
transform: rotateY(180deg);
}
.card-face {
position: absolute;
width: 100%;
height: 100%;
padding: 20px;
box-sizing: border-box;
backface-visibility: hidden;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
.card-front {
font-size: 1em;
font-weight: bold;
}
.card-back {
transform: rotateY(180deg);
font-size: 1.2em;
text-align: center;
line-height: 1.6;
}
.card-wrapper {
display: flex;
flex-direction: column;
align-items: center;
}
.btn-group {
display: flex;
justify-content: center;
flex-wrap: wrap;
gap: 30px;
margin-top: 30px;
}
/* 按钮样式更大更显眼 */
.btn-group .el-button {
padding: 18px 40px;
font-size: 18px;
border-radius: 10px;
font-weight: bold;
min-width: 140px;
transition: all 0.2s ease-in-out;
}
.btn-group .el-button:hover {
transform: scale(1.05);
}
</style>
<!-- 左侧:学习单词区域 -->
<el-col :span="12" class="left-panel" style="height: 100%;">
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
<h2>短期记忆区域</h2>
<div>
<el-button type="primary" @click="openSelectedDialog">查看已选单词</el-button>
<el-button type="success" @click="openDialog" style="margin-left: 10px;">选择单词</el-button>
</div>
</div>
<!-- 单词卡片 -->
<div class="card-container" v-if="reviewList.length">
<div class="card-wrapper">
<div class="card" :class="{ flipped: isFlipped }">
<div class="card-face card-front">
<h1>{{ currentWord.word }}</h1>
<el-button
@click.stop="speakWord(currentWord.word)"
style="background-color: #ffffff; border-color: #ffffff; color: #000000; margin-top: 20px;"
>
🔊 发音
</el-button>
</div>
<div class="card-face card-back">
<h1>{{ currentWord.word }}</h1>
<p><strong>释义:</strong>{{ currentWord.definition }}</p>
<el-button
@click.stop="speakWord(currentWord.word)"
style="background-color: #ffffff; border-color: #ffffff; color: #000000; margin-top: 20px;"
>
🔊 发音
</el-button>
</div>
</div>
<div class="btn-group">
<!-- 正面按钮,点击只翻转,不传数据 -->
<el-button
type="danger"
v-if="!isFlipped"
@click="flipCard"
>忘记</el-button>
<el-button
type="success"
v-if="!isFlipped"
@click="flipCard"
>认识</el-button>
<!-- 背面按钮,点击提交复习结果 -->
<el-button
type="danger"
v-if="isFlipped"
@click="submitReviewResult(false)"
>忘记</el-button>
<el-button
type="success"
v-if="isFlipped"
@click="submitReviewResult(true)"
>认识</el-button>
</div>
</div>
</div>
<!-- 当没有复习单词时显示提示 -->
<div v-else style="text-align:center; margin-top: 50px; font-size: 20px; color: #999;">
无可复习单词,复习完成!
</div>
<!-- 已选单词弹窗 -->
<el-dialog v-model="selectedDialogVisible" title="已选单词列表" width="800px">
<el-table
:data="selectedWords"
style="width: 100%;"
border
@selection-change="handleSelectedChange"
>
<el-table-column type="selection" width="55" />
<el-table-column prop="id" label="ID" width="80" />
<el-table-column prop="word" label="单词" />
<el-table-column prop="definition" label="释义" />
<el-table-column label="操作" width="100">
<template #default="scope">
<el-button type="danger" size="small" @click="removeWord(scope.row)">删除</el-button>
</template>
</el-table-column>
</el-table>
<template #footer>
<span class="dialog-footer">
<el-button @click="selectedDialogVisible = false">关闭</el-button>
<el-button type="danger" :disabled="!selectedToDelete.length" @click="batchRemoveWords">
批量删除({{ selectedToDelete.length }})
</el-button>
</span>
</template>
</el-dialog>
</el-col>
<!-- 右侧:区域 -->
<el-col :span="12" class="right-panel" style="border: 1px solid #eee; padding: 20px;">
<h2>暂未开发</h2>
<p>暂未开发</p>
</el-col>
<!-- 弹窗:选择待学习单词 -->
<el-dialog v-model="dialogVisible" title="选择待学习单词" width="600px">
<el-table :data="pendingWords" style="width: 100%;" @selection-change="handleSelectionChange">
<el-table-column type="selection" width="55" />
<el-table-column prop="word" label="单词" />
<el-table-column prop="definition" label="释义" />
</el-table>
<template #footer>
<span class="dialog-footer">
<el-button @click="dialogVisible = false">取消</el-button>
<el-button type="primary" @click="submitSelectedWords">
确认选择({{ selectedToAdd.length }})
</el-button>
</span>
</template>
</el-dialog>
说明
通过在卡片正面左上角增加一个.score-badge容器来显示当前单词的 score。
currentWord.score即为后台返回的该单词的记忆分数。
样式你可以根据实际需要自定义,这里用了Element UI蓝色调做示例。
这样用户复习时,能清楚看到当前单词的记忆分数,便于明确自己的掌握水平。
如果你需要,我可以帮你修改完整代码或者做更多界面优化!