在首页单击搜索框跳转到搜索页面
在搜索页面输入搜索关键字,显示出匹配的结果
首先添加搜索页面,在app.json中的pages配置项添加pages/search/search,创建搜索页
使用WeUI组件库提供的搜索框组件实现搜索页面,代码如下
搜索页面代码:
<view class="weui-search-bar">
<view class="weui-search-bar__form">
<view class="weui-search-bar__box">
<icon class="weui-icon-search_in-box" type="search" size="14"></icon>
<input type="text" class="weui-search-bar__input"
value="{{searchWords}}" focus="{{searchInputFocus}}"
bindInput="onSearchInputType" />
<!--清空内容的icon-->
<view class="weui-icon-clear" wx:if="{{searchWords.length > 0}}"
bindTap="clearSearchInput">
<icon type="clear" size="14"></icon>
</view>
</view>
<!-- 单击取消后搜索框显示的文字 -->
<label class="weui-search-bar__label" hidden="{{searchInputFocus}}"
bindTap="showSearchInput">
<icon class="weui-icon-search" type="search" size="14"></icon>
<view class="weui-search-bar__text">搜索</view>
</label>
</view>
<view class="weui-search-bar__cancel-btn" hidden="{{!searchInputFocus}}"
bindTap="onTapSearchBtn">
<block wx:if="{{searchWords.length == 0}}">取消</block>
<block wx:else>搜索</block>
</view>
</view>
<!--即时搜索词列表-->
<view class="weui-cells searchbar-result" wx:if="{{wordsList.length > 0}}">
<navigator url="/pages/item/item?id={{item.id}}"
wx:for="{{wordsList}}" wx:key="{{item.id}}"
class="weui-cell">
<view class="weui-cell__bd">
<view>{{item.title}}</view>
</view>
</navigator>
</view>
input组件用于绑定事件
当用户输入时
获取用户输入的内容
从数据库请求search集合
展示实时搜索结果
search.js
Page({
data: {
searchInputFocus: true,
searchWords: "",
wordsList: [],
movies: []
},
onTapSearchBtn() {
this.setData({
searchInputFocus: false,
searchWords: "",
wordsList: []
});
},
showSearchInput() {
this.setData({
searchInputFocus: true
});
},
// 清空输入框中的内容
clearSearchInput() {
this.setData({
searchWords: ""
});
},
// 在搜索框中输入内容
onSearchInputType(e) {
var that = this;
let words = e.detail.value
this.setData({
searchWords: words
});
var db = wx.cloud.database();
db.collection("search")
.get()
.then(res => {
console.log(res)
if (res.data[0].subjects.length) {
that.setData({
wordsList: res.data[0].subjects
});
}
})
}
})