vue实现搜索下载
Vue实现搜索下载功能
搜索功能实现
在Vue中实现搜索功能通常需要使用v-model绑定输入框,并结合计算属性或方法进行过滤。
<template>
<div>
<input v-model="searchQuery" placeholder="搜索内容">
<ul>
<li v-for="item in filteredItems" :key="item.id">
{{ item.name }}
</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
searchQuery: '',
items: [
{ id: 1, name: '文件1' },
{ id: 2, name: '文件2' }
]
}
},
computed: {
filteredItems() {
return this.items.filter(item =>
item.name.toLowerCase().includes(this.searchQuery.toLowerCase())
)
}
}
}
</script>
下载功能实现
使用axios或fetch API进行文件下载,结合Blob对象处理响应。

methods: {
downloadFile(fileId) {
axios.get(`/api/files/${fileId}`, {
responseType: 'blob'
}).then(response => {
const url = window.URL.createObjectURL(new Blob([response.data]))
const link = document.createElement('a')
link.href = url
link.setAttribute('download', 'filename.ext')
document.body.appendChild(link)
link.click()
link.remove()
})
}
}
结合搜索与下载
将两者结合,为搜索结果中的每个项目添加下载按钮。
<li v-for="item in filteredItems" :key="item.id">
{{ item.name }}
<button @click="downloadFile(item.id)">下载</button>
</li>
后端API要求
后端需要提供两个API端点:

- 搜索API:GET
/api/search?q=查询词 - 下载API:GET
/api/files/:id
性能优化
对于大量数据,考虑添加防抖处理搜索输入。
data() {
return {
searchQuery: '',
debounceTimeout: null
}
},
methods: {
onSearchInput() {
clearTimeout(this.debounceTimeout)
this.debounceTimeout = setTimeout(() => {
this.performSearch()
}, 300)
},
performSearch() {
// 实际搜索逻辑
}
}
错误处理
添加下载过程中的错误处理。
downloadFile(fileId) {
axios.get(`/api/files/${fileId}`, {
responseType: 'blob'
}).then(response => {
// 成功处理
}).catch(error => {
console.error('下载失败:', error)
this.$toast.error('文件下载失败')
})
}






