SearchBar.vue
3.37 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
<template>
<FrostedGlass class="px-4 py-2 mx-4 my-3 flex items-center">
<svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 text-gray-400 mr-2" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
</svg>
<template v-if="props.useFormSubmit">
<form @submit.prevent="handleSubmit" action="javascript:return true" class="flex-1">
<input
type="search"
:placeholder="placeholder"
v-model="localValue"
class="bg-transparent outline-none w-full text-gray-700 placeholder-gray-400"
@input="handleSearch"
@blur="handleBlur"
@keyup.enter="handleEnter"
/>
</form>
</template>
<template v-else>
<input
type="search"
:placeholder="placeholder"
v-model="localValue"
class="bg-transparent outline-none flex-1 text-gray-700 placeholder-gray-400"
@input="handleSearch"
@blur="handleBlur"
@keyup.enter="handleEnter"
/>
</template>
</FrostedGlass>
</template>
<script setup>
import { watch, ref } from 'vue'
import { useRouter } from 'vue-router'
import FrostedGlass from './FrostedGlass.vue'
const router = useRouter()
const props = defineProps({
placeholder: {
type: String,
default: '搜索'
},
modelValue: {
type: String,
default: ''
},
isCoursePage: {
type: Boolean,
default: false
},
useFormSubmit: {
type: Boolean,
default: true
}
})
const emit = defineEmits(['search', 'blur', 'update:modelValue'])
const localValue = ref(props.modelValue)
watch(() => props.modelValue, (newValue) => {
localValue.value = newValue
})
/**
* @function handleSearch
* @description 输入变更时触发搜索事件与 v-model 同步(即时搜索)。
* @returns {void}
*/
const handleSearch = () => {
emit('update:modelValue', localValue.value)
emit('search', localValue.value)
}
/**
* @function handleBlur
* @description 失焦时根据页面类型进行跳转或更新 URL 参数。
* - 课程页:跳转至课程列表页并携带关键字参数。
* - 列表页:仅更新当前路由的查询参数。
* @returns {void}
*/
const handleBlur = () => {
const query = localValue.value
emit('blur', query)
// 根据页面类型决定路由行为
if (props.isCoursePage) {
// 在课程页面,跳转到课程列表页
router.push({
path: '/courses-list',
query: { keyword: localValue.value }
})
} else {
// 在课程列表页,只更新URL参数
router.replace({ query: { ...router.currentRoute.value.query, keyword: localValue.value } })
}
}
/**
* @function handleEnter
* @description 键盘回车触发与失焦同等的搜索行为,保证“回车搜索”有效。
* @returns {void}
*/
const handleEnter = () => {
// 复用失焦逻辑以保持一致的路由行为
handleBlur()
}
/**
* @function handleSubmit
* @description 表单提交(移动端键盘“搜索”)触发与失焦同等的搜索行为,增强 iOS 兼容性。
* @returns {void}
*/
const handleSubmit = () => {
handleBlur()
}
</script>