小程序如何封裝自定義組件(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

相關文章
相關標籤/搜索