小程序如何封装自定义组件(Toast)

一、建立和pages 同级的component目录新建一个myToast目录 例如:小程序

二、myToast.wxml文件内容:bash

<!-- 自定义toast组件 -->
<!-- name 模块名称   -->
 <template name="toast" >
 <!-- catchtouchmove=‘xxx’ 遮罩层的滚动穿透 -->
 <!-- isHide 显示消失 -->
  <view class="toast_content_box" wx:if="{{ isHide }}" 
catchtouchmove="preventdefault">  
    <view class="toast_content">  
      <view class='toast_content_text'>
          <!-- 内容 -->
          {{content}} 
      </view>
    </view>  
  </view> 
 </template> 
复制代码

三、myToast.wxss文件样式(根据本身ui样式去写):app

.toast_content_box {  
  overflow: hidden;
  display: flex;  
  width: 100%;  
  height: 100%;  
  justify-content: center;  
  align-items: center;  
  position: fixed;  
  z-index: 999;  
  background-color: rgba(0, 0, 0, 0.3)
} 
.toast_content {  
   width: 50%;
  padding: 30rpx;
  background-color: rgba(0, 0, 0, 0.8);
  border-radius: 20rpx;
}  
.toast_content_text {  
  width: 100%;
  height: 100%;
  background-size: 100% 100%;
  background-repeat: no-repeat;
  text-align: center;
  color: #fff;
  font-size: 28rpx;
  font-weight: 300;
}


复制代码

四、myToast.js文件内容:xss

let _compData = {
  '_toast_.isHide': false,// 控制组件显示隐藏
  '_toast_.content': '',// 显示的内容
}
let toastPannel = {
  // toast显示的方法
  ShowToast: function (data) {
    let self = this;
    this.setData({ '_toast_.isHide': true, '_toast_.content': data });
  },
  // toast隐藏的方法
  HideToast: function (data) {
    let self = this;
    self.setData({ '_toast_.isHide': false })
  },
  // toast显示的方法 2000后隐藏
  ShowToastTime: function (data) {
    let self = this;
    this.setData({ '_toast_.isHide': true, '_toast_.content': data });
    setTimeout(() => {
      this.setData({ '_toast_.isHide': false, '_toast_.content': data });
    }, 2000)
  },
}

function ToastPannel() {
  // 拿到当前页面对象
  let pages = getCurrentPages();
  let curPage = pages[pages.length - 1];
  this.__page = curPage;
  // 小程序最新版把原型链干掉了。。。换种写法
  Object.assign(curPage, toastPannel);
  // 附加到page上,方便访问
  curPage.toastPannel = this;
  // 把组件的数据合并到页面的data对象中
  curPage.setData(_compData);
  return this;
}
module.exports = {
  ToastPannel
}
复制代码

五、全局引入, 在项目中的app.js中将组件脚本引入供全局使用,引入方法:接收暴露出来的构造函数ide

六、 全局引入样式在app.wxss函数

七、在须要使用该组件的页面将模块引入:flex

八、在引入模块组件 同级的js中实例组件的构造函数:ui

九、点击按钮实现效果this

组件比较简单、若是需求不一样另行修改。spa

相关文章
相关标签/搜索