本例以制作一个仿今日头条标题栏组件为例:
参考文献
1.组件模版文件scrollTitle-pannel.wxml:
<template name="scrollTitlePannel">
<scroll-view class="st-scroll" scroll-x="true">
<view class="st-content-view">
<button wx:for="{{titles}}" class="st-title-btn {{index==curIndex ? 'selected': ''}}" data-index="{{index}}" catchtap="__stpannel__clickText" plain="true">{{item}}</button>
</view>
</scroll-view>
</template>
2.组件样式文件scrollTitle-pannel.wxss:
.st-scroll {
height: 80rpx;
}
.st-content-view {
height: 90%;
display: flex;
flex-direction: row;
}
.st-content-view .st-title-btn {
width: auto;
color: black;
flex-shrink: 0;
border-radius: 0rpx;
border: none;
font-size: 36rpx;
}
.st-content-view .selected {
color: red;
font-size: 36rpx;
border-bottom: 2rpx solid red;
}
3.组件逻辑控制文件scrollTitle-pannel.js:
// 组件变量及数据
let _compData = {
'__stpannel__.curIndex': 0
}
// 组件事件
let _compEvent = {
// 按钮方法以及回掉方法调用
__stpannel__clickText: function(e) {
this.setData({'__stpannel__.curIndex': e.target.dataset.index})
typeof this.scrollTitlePannel._configs.callback == "function" &&
this.scrollTitlePannel._configs.callback(e.target.dataset.index)
}
}
let scrollTitlePannel = {
init: function(data) {
if (data) {
// 给回掉方法赋值
Object.assign(this._configs, data)
}
}
}
function ScrollTitlePannel () {
// 回调方法
this._configs = {
callback: null
}
// 当前页面对象
let pages = getCurrentPages()
let curPage = pages[pages.length - 1]
// 把组件的事件赋到当前页面上
Object.assign(curPage, _compEvent)
this.__page = curPage
// 将scrollTitlePannel赋到当前页面,方便后面使用
Object.assign(this, scrollTitlePannel)
curPage.scrollTitlePannel = this
// 把组件的变量数据赋给当前页面的data
curPage.setData(_compData)
return this
}
module.exports = {
ScrollTitlePannel
}
4.使用
首先,在wxml中导入组件模版:
<import src="../commns/scrollTitle-pannel/scrollTitle-pannel.wxml"/>
<template is="scrollTitlePannel" data="{{ ...__stpannel__, titles: titles }}"></template>
然后,在wxss中导入组件样式文件:
@import '../commns/scrollTitle-pannel/scrollTitle-pannel.wxss';
最后,在js文件中导入组件逻辑模块
import { ScrollTitlePannel } from '../commns/scrollTitle-pannel/scrollTitle-pannel'
在data中声明
data: {
ScrollTitlePannel,
},
在onLoad方法中初始化组件及回调方法等:
onLoad: function () {
new ScrollTitlePannel()
this.scrollTitlePannel.init({
callback: this.st_pannel_callback
});
}
st_pannel_callback: function(index) {
console.log("选中了" + index);
},
至此,一个组件的创建到使用的过程就完成了,如果组件是在很多页面使用的话,建议在app.js,app.css中导入组件的相关文件:
app.js
//app.js
import { LoadingPannel } from './pages/commns/loading-pannel/loading-pannel'
App({
LoadingPannel,
})
app.wxss
@import './pages/commns/loading-pannel/loading-pannel.wxss'
网友评论