8_自定义组件和搜索功能
2025/3/24...大约 1 分钟
自定义组件和搜索功能
自定义组件
在项目的根目录 components
目录上,鼠标右键,选择新建组件
,填写组件信息后,点击创建:
在页面以标签形式直接使用即可。
首页搜索功能
通过自定义属性增强组件的通用性
为了增强组件的通用性,我们允许使用者自定义搜索组件的背景颜色
和圆角尺寸
通过 props 定义 bgcolor 和 radius 两个属性,并指定值类型和属性默认值:
自动获取焦点
修改 uni_modules -> uni-search-bar -> components -> uni-search-bar -> uni-search-bar.vue
组件,把 data 中的 show 和 showSync 的值,从默认的 false 改为 true 即可。
return {
show: true,
showSync: true,
searchVal: ''
}
实现搜索框防抖
data() {
timer: null,
}
methods: {
// 每次触发输入都清空定时器,重置定时器。来达到防抖效果
input(val) {
clearTimeout(this.timer)
this.timer = setTimeout(() => {
this.searchValue = val.value
}, 500)
}
}
展示历史搜索
<!-- 搜索历史 -->
<view class="history-box" v-else>
<!-- 标题区域 -->
<view class="history-title">
<text>搜索历史</text>
<uni-icons type="trash" size="17" :color="$uni-text-color" @click="clean"></uni-icons>
</view>
<!-- 列表区域 -->
<view class="history-list">
<uni-tag :text="item" v-for="(item,i) in historyList" :key="i"></uni-tag>
</view>
</view>
data() {
return {
// 搜索历史的数据
historyList: ['a', 'app', 'apple']
};
},
将搜索关键词存入 historyList
onLoad() {
this.historyList = JSON.parse(uni.getStorageSync('kw' || '[]'))
},
method: {
saveSearchHistory() {
const set = new Set(this.historyList)
// 去掉原来的
set.delete(this.searchValue)
// 放在最新
set.add(this.searchValue)
this.historyList = Array.from(set)
// 将搜索历史记录持久存储到本地
uni.setStorageSync('kw', JSON.stringify(this.historyList))
},
// 清空方法
clean() {
this.historyList = []
uni.setStorageSync('kw', '[]')
}
}