vue实现collapse搜索
实现折叠搜索功能
在Vue中实现折叠搜索功能可以通过结合v-show或v-if指令与数据绑定完成。以下是具体实现方法:
基础实现方式
创建可折叠的搜索框组件:
<template>
<div>
<button @click="toggleSearch">Toggle Search</button>
<div v-show="isSearchVisible">
<input v-model="searchQuery" placeholder="Search...">
<button @click="performSearch">Search</button>
</div>
</div>
</template>
<script>
export default {
data() {
return {
isSearchVisible: false,
searchQuery: ''
}
},
methods: {
toggleSearch() {
this.isSearchVisible = !this.isSearchVisible
},
performSearch() {
this.$emit('search', this.searchQuery)
}
}
}
</script>
添加动画效果
使用Vue的transition组件实现平滑的展开/折叠动画:
<transition name="slide-fade">
<div v-show="isSearchVisible" class="search-container">
<input v-model="searchQuery">
</div>
</transition>
<style>
.slide-fade-enter-active, .slide-fade-leave-active {
transition: all 0.3s ease;
}
.slide-fade-enter, .slide-fade-leave-to {
transform: translateY(-10px);
opacity: 0;
}
.search-container {
margin: 10px 0;
}
</style>
结合搜索功能
实现完整的搜索功能,包括结果展示:
<template>
<div>
<button @click="toggleSearch">{{ isSearchVisible ? 'Hide' : 'Show' }} Search</button>
<transition name="fade">
<div v-show="isSearchVisible">
<input v-model="searchTerm" @input="search">
<div v-if="searchResults.length">
<ul>
<li v-for="result in searchResults" :key="result.id">
{{ result.name }}
</li>
</ul>
</div>
<div v-else-if="searchTerm && !searchResults.length">
No results found
</div>
</div>
</transition>
</div>
</template>
<script>
export default {
data() {
return {
isSearchVisible: false,
searchTerm: '',
searchResults: [],
items: [
{ id: 1, name: 'Apple' },
{ id: 2, name: 'Banana' },
{ id: 3, name: 'Orange' }
]
}
},
methods: {
toggleSearch() {
this.isSearchVisible = !this.isSearchVisible
if (!this.isSearchVisible) {
this.searchTerm = ''
this.searchResults = []
}
},
search() {
if (!this.searchTerm) {
this.searchResults = []
return
}
const term = this.searchTerm.toLowerCase()
this.searchResults = this.items.filter(item =>
item.name.toLowerCase().includes(term)
)
}
}
}
</script>
使用第三方库增强功能
对于更复杂的需求,可以结合第三方库如Fuse.js实现模糊搜索:
import Fuse from 'fuse.js'
// 在methods中添加
advancedSearch() {
const options = {
keys: ['name'],
threshold: 0.4
}
const fuse = new Fuse(this.items, options)
this.searchResults = this.searchTerm
? fuse.search(this.searchTerm).map(r => r.item)
: []
}
响应式设计考虑
确保搜索组件在不同屏幕尺寸下表现良好:
@media (max-width: 768px) {
.search-container {
width: 100%;
}
input[type="text"] {
width: calc(100% - 20px);
}
}
键盘快捷键支持
添加键盘快捷键提升用户体验:
mounted() {
window.addEventListener('keydown', this.handleKeyPress)
},
beforeDestroy() {
window.removeEventListener('keydown', this.handleKeyPress)
},
methods: {
handleKeyPress(e) {
if (e.ctrlKey && e.key === 'k') {
e.preventDefault()
this.toggleSearch()
if (this.isSearchVisible) {
this.$nextTick(() => {
this.$refs.searchInput.focus()
})
}
}
}
}
以上实现方式可根据具体项目需求进行调整和组合,创建适合的折叠搜索功能。







