效果图:
定义一个公共的搜索组件,该组件不做任何的网络请求操作,只做一个“输入”的操作,然后将输入的结果传给页面或者是上层组件。
wxml
<view class="dx-search-bar">
<view class="dx-search-bar-from">
<!-- 搜索框的输入区 -->
<view class="dx-search-bar-box">
<icon class="dx-icon-search" type="search" size="12" />
<input type="text" class="dx-search-bar-input" placeholder="{{placeholder}}" bindblur="blur" />
</view>
<!-- 搜索框 的标签 -->
<label class="dx-search-bar-label">
<text class="dx-search-bar-text">搜索</text>
</label>
</view>
</view>
css
.dx-search-bar-from {
display: flex;
justify-content: space-between;
}
.dx-search-bar-input {
width: 460rpx;
display: block;
padding-left: 10px;
}
.dx-search-bar-box {
display: flex;
align-items: center;
border: 1px solid green;
border-radius: 5px;
padding: 0 5px;
}
.dx-search-bar-label {
font-size: 14px;
}
当输入结束后,input失去焦点时组件将参数传递给上层组件。这时自定义组件需要触发事件才能将参数传给上层组件,该事件是triggerEvent方法,指定了事件名、detail和事件选项。
blur函数
blur(e) {
console.log(e)
this.setData({
searchValue: e.detail.value
})
// 组件向页面传递参数
this.triggerEvent('realNameConfirm', e.detail.value)
},
父组件或者是页面向组件传递参数,通过自定义组件的属性向组件传递参数,在搜索组件内设置组件属性的类型后,该属性值就是父组件向搜索组件传递的参数。搜索组件的js代码:
// pages/ui_component/searchbar/searchbar.js
Component({
/**
* 组件的属性列表
*/
properties: {
placeholder: {
type: String,
value: ""
}
},
/**
* 组件的初始数据
*/
data: {
placeholder: "",
searchValue: ""
},
/**
* 组件的方法列表
*/
methods: {
blur(e) {
console.log(e)
this.setData({
searchValue: e.detail.value
})
// 组件向页面传递参数
this.triggerEvent('realNameConfirm', e.detail.value)
},
}
})
文章评论