很简单:记录一下
想组件封装,直接右键:点击新建点击Component
基本结构是这样的
这里以封装搜索框为例子
直接上代码:
js代码:
// components/search.js
Component({
/**
* 组件的属性列表
*/
properties: {
placeholder: {
type: String,
value: '请输入',
},
},
/**
* 页面的初始数据
*/
data: {
showClear: false,
inputValue: null,
},
methods: {
changeEvent(e) {
this.setData({ showClear: e.detail.value.length > 0 ? true : false });
this.triggerEvent('changeEvent', e.detail.value);
},
bindconfirm(e) {
this.triggerEvent('confirmEvent', e.detail.value);
},
loseFouse() {
setTimeout(() => {
this.setData({ showClear: false });
}, 100);
this.triggerEvent('loseFouse',);
},
bindfocus(e) {
this.setData({ showClear: e.detail.value.length > 0 ? true : false });
this.triggerEvent('bindfocus');
},
clearEvent() {
console.log('点击了');
this.setData({
showClear: false,
inputValue: '',
});
this.triggerEvent('clearEvent');
},
},
bindkeyboardheightchange(e) {
this.triggerEvent('bindkeyboardheightchange',e.detail);
},
});
wxml:其中<van-icon>是图标:可以去掉;image 的src是删除的图片,自行添加
<view class="search-view">
<view style="width: 100%;display: flex; align-items: center;">
<van-icon name="search" size="16px" color="#a9aeb8"/>
<input style="flex:1;" placeholder='{{placeholder}}' placeholder-class="phStyle" bindinput="changeEvent" value="{{inputValue}}" bindblur="loseFouse" bindfocus="bindfocus" bindconfirm="bindconfirm" bindkeyboardheightchange="bindkeyboardheightchange" />
<image wx:if="{{showClear}}" src="/images/fans/delete.png" style="margin-left: 10px;width: 14px;height: 14px;" bindtap="clearEvent"></image>
</view>
</view>
wxss
/* components/search.wxss */
.search-view {
display: flex;
background-color: #ebebeb;
border-radius: 25px;
padding: 4px 15px 4px 15px;
align-items: center;
}
.phStyle {
color: #a9aeb8;
font-size: 13px;
}
使用:
1、引入
{
"usingComponents": {
"search": "/components/search/search"
}
}
2、wxml
<search style="flex: 1;" bind:changeEvent="changeEvent" bind:clearEvent="clearEvent" bind:confirmEvent="confirmEvent" placeholder="请输入姓名或身份证后6位或手机号"></search>
3、需注意的时,最终拿到的值是e.detail
changeEvent(e) {
console.log(e.detail);
},