微信小程序 自定義組件(modal) 引入組件


項目結構:

步驟一:創建組件

聲明這一組文件為自定義組件

modal.json

{
  "component": true, // 自定義組件聲明
  "usingComponents": {} // 可選項,用於引用別的組件
}

步驟二:編寫組件代碼

1.邏輯層

modal.js

Component({
  properties: {
    modalHidden: {
      type: Boolean,
      value: true
    }, //這里定義了modalHidden屬性,屬性值可以在組件使用時指定.寫法為modal-hidden  
    modalMsg: {
      type: String,
      value: ' ',
    }
  },
  data: {
    // 這里是一些組件內部數據  
    text: "text",
  },
  methods: {
    // 這里放置自定義方法  
    modal_click_Hidden: function () {
      this.setData({
        modalHidden: true,
      })
    },
    // 確定  
    Sure: function () {
      console.log(this.data.text)
    }
  }
})

2.頁面布局

modal.wxml

<view hidden='{{modalHidden}}'>  
  <view class='mask_layer' bindtap='modal_click_Hidden' />  
  <view class='modal_box'>  
    <view class="title">提示</view>  
    <view class='content'>  
      <text class='modalMsg'>{{modalMsg}}</text>  
    </view>  
    <view class='btn'>  
      <view bindtap='modal_click_Hidden' class='cancel'>取消</view>  
      <view bindtap='Sure' class='Sure'>確定</view>  
    </view>  
  </view>  
</view>

3.樣式

modal.wxss

.mask_layer {  
  width: 100%;  
  height: 100%;  
  position: fixed;  
  z-index: 1000;  
  background: #000;  
  opacity: 0.5;  
  overflow: hidden;  
}  
.modal_box {  
  width: 76%;  
  overflow: hidden;  
  position: fixed;  
  top: 50%;  
  left: 0;  
  z-index: 1001;  
  background: #fafafa;  
  margin: -150px 12% 0 12%;  
  border-radius: 3px;  
}  
  
.title {  
  padding: 15px;  
  text-align: center;  
  background-color: gazure;  
}  
  
.content {  
  overflow-y: scroll; /*超出父盒子高度可滾動*/  
}  
  
.btn {  
  width: 100%;  
  margin-top: 65rpx;  
  display: flex;  
  flex-direction: row;  
  align-items: center;  
  justify-content: space-between;  
  box-sizing: border-box;  
  background-color: white;  
}  
  
.cancel {  
  width: 100%;  
  padding: 10px;  
  text-align: center;  
  color: red;  
}  
  
.Sure {  
  width: 100%;  
  padding: 10px;  
  background-color: gainsboro;  
  text-align: center;  
}  
  
.modalMsg {  
  text-align: center;  
  margin-top: 45rpx;  
  display: block;  
}

步驟三:使用組件

這里我是在 pages/index/index 頁面調用 pages/modal/modal 自定義組件

首先在index.json中進行引用說明, 這里是設置自定義組件的標簽名和引用路徑

{
  "usingComponents": {
    "modal": "../../component/modal/modal"
  }
}

然后在index.wxml調用組件

<!-- 調用modal組件 -->  
<modal modal-hidden="{{is_modal_Hidden}}" modal-msg="{{is_modal_Msg}}"/>

在index.js綁定數據

Page({  
  data: {  
    is_modal_Hidden:false,  
    is_modal_Msg:'我是一個自定義組件'  
  }  
})

步驟四:效果圖


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM