feat(script-favorite): update toggleFavorite to use backend API
- Import toggleFavoriteScript from epicScript service - Change toggleFavorite from sync local-only to async with API call - Implement optimistic update pattern: update local cache first, then call backend - Rollback on API failure with error toast - Preserves localFavorites for offline/fast-render scenarios
This commit is contained in:
@@ -149,6 +149,7 @@
|
|||||||
<script setup>
|
<script setup>
|
||||||
import { computed, ref } from 'vue'
|
import { computed, ref } from 'vue'
|
||||||
import { useAppStore } from '../../stores/app.js'
|
import { useAppStore } from '../../stores/app.js'
|
||||||
|
import { toggleFavoriteScript } from '../../services/epicScript.js'
|
||||||
|
|
||||||
const store = useAppStore()
|
const store = useAppStore()
|
||||||
const activeType = ref('long')
|
const activeType = ref('long')
|
||||||
@@ -316,15 +317,34 @@ const toggleScriptMenu = (script) => {
|
|||||||
activeMenuId.value = activeMenuId.value === id ? '' : id
|
activeMenuId.value = activeMenuId.value === id ? '' : id
|
||||||
}
|
}
|
||||||
|
|
||||||
const toggleFavorite = (script) => {
|
const toggleFavorite = async (script) => {
|
||||||
const favorite = isFavorite(script)
|
const wasFav = isFavorite(script)
|
||||||
|
// 乐观更新:先改本地缓存
|
||||||
const next = { ...localFavorites.value }
|
const next = { ...localFavorites.value }
|
||||||
if (favorite) delete next[String(script.id)]
|
if (wasFav) {
|
||||||
else next[String(script.id)] = true
|
delete next[String(script.id)]
|
||||||
|
} else {
|
||||||
|
next[String(script.id)] = true
|
||||||
|
}
|
||||||
localFavorites.value = next
|
localFavorites.value = next
|
||||||
uni.setStorageSync('script_favorites', next)
|
uni.setStorageSync('script_favorites', next)
|
||||||
closeScriptMenu()
|
closeScriptMenu()
|
||||||
uni.showToast({ title: favorite ? '已取消收藏' : '已收藏', icon: 'success' })
|
|
||||||
|
try {
|
||||||
|
const result = await toggleFavoriteScript(script.id)
|
||||||
|
uni.showToast({ title: result.isFavorited ? '已收藏' : '已取消收藏', icon: 'success' })
|
||||||
|
} catch (error) {
|
||||||
|
// 回滚乐观更新
|
||||||
|
const restored = { ...localFavorites.value }
|
||||||
|
if (wasFav) {
|
||||||
|
restored[String(script.id)] = true
|
||||||
|
} else {
|
||||||
|
delete restored[String(script.id)]
|
||||||
|
}
|
||||||
|
localFavorites.value = restored
|
||||||
|
uni.setStorageSync('script_favorites', restored)
|
||||||
|
uni.showToast({ title: error?.message || '操作失败', icon: 'none' })
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const continueScript = (script) => {
|
const continueScript = (script) => {
|
||||||
|
|||||||
Reference in New Issue
Block a user