在小程序开发过程中,小编就在想可不可以把一些东西开发成组件的形式,减少页面的代码量和开发时间。提高开发效率。仔细阅读小程序开发文档,发现在小程序开发指南下有一个自定义组键,根据小程序开发规则便可以编写自己的组键了。
这里以公告为示例
注意事项:
1、组件创建
创建Component类型。
2、引入组件,注意:组件引入分为全局引入和局部引入。在json里面配置引入规则
(1)、全局引入。在app.json里配置
{
"pages":[
],
"usingComponents":{
"my-notice":"/assembly/notice/notice"//组件目录:/根目录/组件文件夹/组件wxml文件
}
}
(2)、局部引入,页面json里面配置
{
"usingComponents":{
"my-notice":"/assembly/notice/notice"//组件目录:/根目录/组件文件夹/组件wxml文件
}
}
2、wxml页面引用
<my-notice nitoce="{{notice}}">
<view>这里是<slot>用于承载组件引用时提供的子节点</view>
</my-notice>
3、示例:组件wxml编写,<slot>用于承载组件引用时提供的子节点。
(1)、wxml页面编写和page页面没什么差别
<view class="my-notice">
<view class="notice-box">
<view class="notice-animation">
<slot></slot>
</view>
</view>
</view>
(2)、wxss页面编写和page(wxss)页面没什么差别
.my-notice{
width: 100%;
height: 80rpx;
line-height: 80rpx;
padding: 0 30rpx;
box-sizing: border-box;
background-color: #ffffff;
}
.notice-box{
width: 100%;
overflow: hidden;
}
.notice-animation{
color: #5e5e5e;
white-space: nowrap;
font-size: 28rpx;
}
(3)、js页面编写和page(js)页面差别在于页面周期
// assembly/notice/notice.js
Component({
/**
* 组件的属性列表
* 用于接收页面传递过来的参数,type为参数类型,value为接收的参数,可设置默认参数
*/
properties: {
notice:{
type:Array,
value:[]
}
},
/**
* 组件的初始数据
*/
data: {
noticeTimer:15000
},
/**
* 组件页面生命周期
*/
lifetimes:{
attached: function() {
this.notice();
}
},
/**
* 组件的方法列表
*/
methods: {
/**
* 公告内容获取
* @param {*} time
*/
notice:function(){
var _this = this;
var JqueryRect = '';
var Jquery = wx.createSelectorQuery();
Jquery.select(".notice-box").boundingClientRect();
console.log(Jquery)
for(var i=0;i<this.properties.text.length;i++){
Jquery.select(".notice-item"+i).boundingClientRect();
}
Jquery.exec((rect)=>{
console.log(rect)
let textWidth = 0;
let wrapWidth = 0;
for(var i=0;i<rect.length;i++){
if(i ==0 ){
wrapWidth = rect[i]?rect[i].width:'100%'
}
if(i>0){
textWidth += rect[i]?rect[i].width:"-200%"
}
}
_this.setData({
wrapWidth: wrapWidth,
textWidth: textWidth
}, () => {
_this.noticeAni(_this.data.noticeTimer)
})
})
},
noticeAni(time){
var _this = this;
_this.animate('.notice-animation',[{
translateX:"100%"
},{
translateX: -_this.data.textWidth
}],time,function () {
this.noticeAni(_this.data.noticeTimer)
}.bind(this));
}
}
})
4、页面通讯
(1)、页面向组件传值,my-notice是自己命名的组件在页面的引用名称,notice是自定义的组件接收参数,{{notice}}是自定义的组件接收数据。
<!--Component.wxml-->
<view bindtap="bindCancel">
{{notice}}
<slot></slot>
</view>
//Component.js
Component({
properties:{
notice:{
type:String,//参数类型
value:"你好!这里是组件内容",默认值
}
}
/**
* 组件的方法列表
*/
methods: {
bindCancel:function(){
this.triggerEvent('customevent', {notice: "组件开发你学会了吗?"})
},
}
})
<!--页面,index.wxml-->
<my-notice nitoce="{{notice}}" bindcustomevent="pageEvent">
<view>哈哈哈!没想到我也在里面吧</view>
</my-notice>
//index.js
Page({
data:{
notice:'开始你的组件学习之旅吧!'
},
pageEvent:function(e){
this.setData({
notice:e.detail.notice
})
}
})
网友评论