在 UniApp 中实现搜索功能,可以通过以下步骤完成:
1. 页面布局
使用 input 组件作为搜索框,button 组件作为搜索按钮,并绑定事件。
<template>
<view class="search-container">
<input
v-model="keyword"
placeholder="请输入搜索内容"
@confirm="handleSearch"
class="search-input"
/>
<button @tap="handleSearch" class="search-btn">搜索</button>
</view>
</template>
2. 数据绑定与事件处理
在 script 部分定义数据和方法:
<script>
export default {
data() {
return {
keyword: '' // 绑定输入框内容
};
},
methods: {
handleSearch() {
if (!this.keyword.trim()) {
uni.showToast({
title: '请输入搜索内容',
icon: 'none'
});
return;
}
// 执行搜索逻辑,例如跳转到搜索结果页或过滤本地数据
console.log('搜索关键词:', this.keyword);
// 示例:跳转到搜索结果页,传递关键词
uni.navigateTo({
url: `/pages/searchResult/searchResult?keyword=${this.keyword}`
});
}
}
};
</script>
3. 样式调整
添加简单样式优化布局:
<style scoped>
.search-container {
display: flex;
padding: 20rpx;
background: #f8f8f8;
}
.search-input {
flex: 1;
height: 70rpx;
padding: 0 20rpx;
background: #fff;
border-radius: 8rpx;
margin-right: 20rpx;
}
.search-btn {
width: 140rpx;
height: 70rpx;
line-height: 70rpx;
background: #007aff;
color: #fff;
border-radius: 8rpx;
}
</style>
4. 功能扩展建议
- 防抖处理:避免频繁触发搜索,可使用
setTimeout 或 Lodash 的 debounce。
- 本地历史记录:通过
uni.setStorageSync 存储搜索记录。
- 实时搜索:结合
@input 事件和防抖实现输入时实时筛选。
示例:防抖实现
data() {
return {
keyword: '',
timer: null
};
},
methods: {
handleInput() {
clearTimeout(this.timer);
this.timer = setTimeout(() => {
this.handleSearch();
}, 500); // 延迟500毫秒
}
}
以上代码提供了基础搜索功能的实现,可根据实际需求调整逻辑和样式。