feat:搜索浮窗,和接口调用

This commit is contained in:
小张 2025-09-09 15:00:37 +08:00
parent 9b601f9117
commit b283f4e3c7
3 changed files with 451 additions and 4 deletions

View File

@ -42,9 +42,24 @@
<!-- 搜索框 --> <!-- 搜索框 -->
<div class="search-section"> <div class="search-section">
<div class="search-box"> <div class="search-box" ref="searchBoxRef">
<img src="/nav-icons/搜索.png" alt="" class="search-icon" /> <img src="/nav-icons/搜索.png" alt="" class="search-icon" />
<input type="text" placeholder="请输入感兴趣的课程" class="search-input" /> <input
type="text"
placeholder="请输入感兴趣的课程"
class="search-input"
v-model="searchKeyword"
@focus="showSearchDropdown = true"
@keyup.enter="handleSearch"
/>
<!-- 搜索下拉框 -->
<SearchDropdown
:visible="showSearchDropdown"
@search="handleSearchFromDropdown"
@close="showSearchDropdown = false"
ref="searchDropdownRef"
/>
</div> </div>
</div> </div>
@ -136,6 +151,7 @@ import { NDropdown, NIcon } from 'naive-ui'
import LoginModal from '@/components/auth/LoginModal.vue' import LoginModal from '@/components/auth/LoginModal.vue'
import RegisterModal from '@/components/auth/RegisterModal.vue' import RegisterModal from '@/components/auth/RegisterModal.vue'
import SafeAvatar from '@/components/common/SafeAvatar.vue' import SafeAvatar from '@/components/common/SafeAvatar.vue'
import SearchDropdown from '@/components/search/SearchDropdown.vue'
const router = useRouter() const router = useRouter()
const route = useRoute() const route = useRoute()
@ -200,6 +216,12 @@ const registerModalVisible = ref(false)
const showLanguageDropdown = ref(false) const showLanguageDropdown = ref(false)
const languageSwitcherRef = ref<HTMLElement | null>(null) const languageSwitcherRef = ref<HTMLElement | null>(null)
//
const searchKeyword = ref('')
const showSearchDropdown = ref(false)
const searchBoxRef = ref<HTMLElement | null>(null)
const searchDropdownRef = ref<InstanceType<typeof SearchDropdown> | null>(null)
// //
const languageOptions = computed(() => [ const languageOptions = computed(() => [
{ {
@ -278,6 +300,36 @@ const getLanguageName = (lang: string): string => {
return languageMap[lang] || '中文' return languageMap[lang] || '中文'
} }
//
const handleSearch = () => {
if (searchKeyword.value.trim()) {
performSearch(searchKeyword.value.trim())
}
}
const handleSearchFromDropdown = (keyword: string) => {
searchKeyword.value = keyword
performSearch(keyword)
}
const performSearch = (keyword: string) => {
console.log('🔍 执行搜索:', keyword)
//
if (searchDropdownRef.value) {
searchDropdownRef.value.saveRecentSearch(keyword)
}
//
router.push({
path: '/search',
query: { q: keyword }
})
//
showSearchDropdown.value = false
}
const handleLearningCenter = () => { const handleLearningCenter = () => {
@ -634,10 +686,15 @@ const handleAuthSuccess = () => {
// handleClickOutside // handleClickOutside
const handleClickOutside = (event: MouseEvent) => { const handleClickOutside = (event: MouseEvent) => {
// //
if (languageSwitcherRef.value && !languageSwitcherRef.value.contains(event.target as Node)) { if (languageSwitcherRef.value && !languageSwitcherRef.value.contains(event.target as Node)) {
showLanguageDropdown.value = false showLanguageDropdown.value = false
} }
//
if (searchBoxRef.value && !searchBoxRef.value.contains(event.target as Node)) {
showSearchDropdown.value = false
}
} }
// //
@ -863,6 +920,7 @@ watch(() => route.path, () => {
.search-box { .search-box {
/* border-left: 1px solid #ececec; /* border-left: 1px solid #ececec;
border-right: 1px solid #ececec; */ border-right: 1px solid #ececec; */
position: relative;
display: flex; display: flex;
align-items: center; align-items: center;
padding: 22px 16px; padding: 22px 16px;

View File

@ -0,0 +1,384 @@
<template>
<div class="search-dropdown" v-if="visible">
<div class="search-container">
<!-- 热门搜索 -->
<div class="search-section">
<div class="section-header">
<h3 class="section-title">热门搜索</h3>
</div>
<div class="hot-search-list">
<div
v-for="(item, index) in hotSearchList"
:key="item.id || index"
class="hot-search-item"
@click="handleSearchClick(item.keyword)"
>
<img src="https://lanhu-oss-proxy.lanhuapp.com/SketchPng86b5edcdd0d6d6bd7275b4c04630b14d852bddab1f172c0abf2f0e35aec35768" alt="搜索" class="search-icon" />
<span class="search-text">{{ item.keyword }}</span>
<span class="search-count">{{ item.count }}+课程</span>
</div>
</div>
</div>
<!-- 最近搜索 -->
<div class="search-section" v-if="isLoggedIn && recentSearchList.length > 0">
<div class="section-header">
<h3 class="section-title">最近搜索</h3>
<button class="clear-all-btn" @click="clearAllRecentSearch">删除全部</button>
</div>
<div class="recent-search-list">
<div
v-for="(item, index) in recentSearchList"
:key="index"
class="recent-search-item"
@click="handleSearchClick(item)"
>
<img src="https://lanhu-oss-proxy.lanhuapp.com/SketchPng2fed0d5a23626a57e891038b8d9898f3e7e3d997c740e810d14cba77dbf65bd9" alt="最近搜索" class="recent-icon" />
<span class="recent-text">{{ item }}</span>
<button class="delete-btn" @click.stop="deleteRecentSearch(index)">
<img
class="delete-icon"
referrerpolicy="no-referrer"
src="https://lanhu-oss-proxy.lanhuapp.com/SketchPng9091e6ef98dfc2513c9530794244c6258e5360d316fcc770d6309e2fb41a0665"
alt="删除"
/>
</button>
</div>
</div>
</div>
</div>
</div>
</template>
<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useUserStore } from '@/stores/user'
import { ApiRequest } from '@/api/request'
// Props
interface Props {
visible: boolean
}
const props = defineProps<Props>()
// Emits
const emit = defineEmits<{
search: [keyword: string]
close: []
}>()
// Store
const userStore = useUserStore()
//
const hotSearchList = ref<any[]>([])
const recentSearchList = ref<string[]>([])
//
const isLoggedIn = computed(() => !!userStore.user)
//
interface HotSearchItem {
id?: string
keyword: string
count: number
}
//
const fetchHotSearch = async () => {
try {
console.log('🚀 获取热门搜索数据...')
const response = await ApiRequest.get<HotSearchItem[]>('/aiol/index/hot_search')
console.log('📊 热门搜索API响应:', response)
if (response.data) {
const apiResponse = response.data as any
// {success, code, result}
if (typeof apiResponse === 'object' && ('success' in apiResponse || 'code' in apiResponse)) {
const success = apiResponse.success === true || apiResponse.code === 200 || apiResponse.code === 0
if (success && apiResponse.result) {
hotSearchList.value = apiResponse.result
} else {
console.error('❌ 获取热门搜索失败:', apiResponse.message || '未知错误')
// 使
hotSearchList.value = getMockHotSearch()
}
} else if (Array.isArray(apiResponse)) {
//
hotSearchList.value = apiResponse
} else {
console.error('❌ 热门搜索数据格式错误')
hotSearchList.value = getMockHotSearch()
}
} else {
console.error('❌ 热门搜索响应为空')
hotSearchList.value = getMockHotSearch()
}
console.log('✅ 热门搜索数据加载完成:', hotSearchList.value)
} catch (error) {
console.error('❌ 获取热门搜索异常:', error)
// 使
hotSearchList.value = getMockHotSearch()
}
}
//
const getMockHotSearch = (): HotSearchItem[] => {
return [
{ id: '1', keyword: 'IT与软件', count: 10 },
{ id: '2', keyword: '设计', count: 10 },
{ id: '3', keyword: '数字营销', count: 10 }
]
}
//
const loadRecentSearch = () => {
if (isLoggedIn.value) {
const userId = userStore.user?.id || userStore.user?.username || 'default'
const storageKey = `recent_search_${userId}`
const stored = localStorage.getItem(storageKey)
if (stored) {
try {
recentSearchList.value = JSON.parse(stored)
} catch (error) {
console.error('解析最近搜索记录失败:', error)
recentSearchList.value = []
}
}
}
}
//
const saveRecentSearch = (keyword: string) => {
if (!isLoggedIn.value || !keyword.trim()) return
const userId = userStore.user?.id || userStore.user?.username || 'default'
const storageKey = `recent_search_${userId}`
//
const filtered = recentSearchList.value.filter(item => item !== keyword)
recentSearchList.value = [keyword, ...filtered].slice(0, 10) // 10
// localStorage
localStorage.setItem(storageKey, JSON.stringify(recentSearchList.value))
}
//
const handleSearchClick = (keyword: string) => {
console.log('🔍 搜索关键词:', keyword)
saveRecentSearch(keyword)
emit('search', keyword)
emit('close')
}
//
const deleteRecentSearch = (index: number) => {
recentSearchList.value.splice(index, 1)
if (isLoggedIn.value) {
const userId = userStore.user?.id || userStore.user?.username || 'default'
const storageKey = `recent_search_${userId}`
localStorage.setItem(storageKey, JSON.stringify(recentSearchList.value))
}
}
//
const clearAllRecentSearch = () => {
recentSearchList.value = []
if (isLoggedIn.value) {
const userId = userStore.user?.id || userStore.user?.username || 'default'
const storageKey = `recent_search_${userId}`
localStorage.removeItem(storageKey)
}
}
//
onMounted(() => {
fetchHotSearch()
loadRecentSearch()
})
//
defineExpose({
saveRecentSearch,
loadRecentSearch
})
</script>
<style scoped>
.search-dropdown {
position: absolute;
top: 100%;
left: -33%;
z-index: 1000;
margin-top: -8px;
}
.search-container {
width: 704px;
background: #FFFFFF;
box-shadow: 0px 2px 24px 0px rgba(220, 220, 220, 0.5);
border-radius: 8px;
padding: 24px;
}
.search-section {
margin-bottom: 32px;
}
.search-section:last-child {
margin-bottom: 0;
}
.section-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 16px;
}
.section-title {
width: 118px;
height: 22px;
font-family: PingFangSC, PingFang SC, -apple-system, BlinkMacSystemFont, sans-serif;
font-weight: 400;
font-size: 16px;
color: #000000;
line-height: 22px;
text-align: left;
font-style: normal;
margin: 0;
}
.clear-all-btn {
background: none;
border: none;
color: #999;
font-size: 14px;
cursor: pointer;
padding: 4px 8px;
border-radius: 4px;
transition: all 0.2s;
}
.clear-all-btn:hover {
background-color: #f5f5f5;
color: #666;
}
.hot-search-list {
display: flex;
flex-direction: column;
gap: 12px;
}
.hot-search-item {
display: flex;
align-items: center;
gap: 12px;
padding: 8px 12px;
border-radius: 6px;
cursor: pointer;
transition: all 0.2s;
}
.hot-search-item:hover {
background-color: #f8f9fa;
}
.search-icon {
width: 16px;
height: 16px;
object-fit: contain;
}
.search-text {
flex: 1;
font-family: PingFangSC, PingFang SC, -apple-system, BlinkMacSystemFont, sans-serif;
font-weight: 400;
font-size: 16px;
color: #000000;
line-height: 22px;
}
.search-count {
font-size: 14px;
color: #1890ff;
background-color: #e6f7ff;
padding: 2px 8px;
border-radius: 12px;
}
.recent-search-list {
display: flex;
flex-direction: column;
gap: 8px;
}
.recent-search-item {
display: flex;
align-items: center;
gap: 12px;
padding: 8px 12px;
border-radius: 6px;
cursor: pointer;
transition: all 0.2s;
}
.recent-search-item:hover {
background-color: #f8f9fa;
}
.recent-icon {
width: 16px;
height: 16px;
object-fit: contain;
}
.recent-text {
flex: 1;
width: 480px;
height: 24px;
font-family: PingFangSC, PingFang SC, -apple-system, BlinkMacSystemFont, sans-serif;
font-weight: 400;
font-size: 16px;
color: #666666;
line-height: 24px;
text-align: left;
font-style: normal;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.delete-btn {
background: none;
border: none;
cursor: pointer;
padding: 4px;
border-radius: 4px;
transition: all 0.2s;
opacity: 0;
display: flex;
align-items: center;
justify-content: center;
}
.recent-search-item:hover .delete-btn {
opacity: 1;
}
.delete-btn:hover {
background-color: #f5f5f5;
}
.delete-icon {
width: 14px;
height: 14px;
object-fit: contain;
}
</style>

View File

@ -114,7 +114,7 @@
<div class="form-footer"> <div class="form-footer">
<p class="agreement-text"> <p class="agreement-text">
{{ isRegisterMode ? '登录即代表阅读并同意' : '登录即同意我们的用户协议' }} {{ isRegisterMode ? '登录即代表阅读并同意' : '登录即同意我们的用户协议' }}
<n-button text type="primary" size="small">服务协议和隐私政策</n-button> <n-button text type="primary" size="small" @click="goToServiceAgreement">服务协议和隐私政策</n-button>
</p> </p>
</div> </div>
</div> </div>
@ -336,6 +336,11 @@ const handleSubmit = async () => {
userStore.isLoading = false userStore.isLoading = false
} }
} }
//
const goToServiceAgreement = () => {
router.push('/service-agreement')
}
</script> </script>
<style scoped> <style scoped>