天天看点

微信小程序 - 使用自定义组件

在使用中,自定义组件的使用是必不可少的:

第一步:在pages同一等级创建component文件,在component创建组件gameOver。这是一个弹框

gameOver.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'>最终得分:{{score}}</text>  
      <text class='modalMsg'>最终排名:{{ranking}}</text>
    </view>  
    <view class='btn'>   
      <view bindtap='Sure' class='Sure'>确定</view>  
    </view>  
  </view>  
</view>
           

gameOver.wxss:

.mask_layer {  
  width: 100%;  
  height: 100%; 
  top:0px;
  left:0px;
  position:fixed; 
  z-index: 1000; 
  background:rgba(0, 0, 0, 0.8);  
  overflow: hidden;  
}  
.modal_box {  
  width: 76%;  
  overflow: hidden;  
  position: fixed;  
  top: 50%;  
  left: 0;  
  z-index: 1001;    
  margin: -150px 12% 0 12%;  
  border-radius: 3px;  
}  
  
.title {  
  padding: 15px;  
  text-align: center; 
  font-size:44rpx;
  font-weight:bolder;
  color:#fff;
  letter-spacing:5rpx;
  font-family:Arial,'Times New Roman','Microsoft YaHei',SimHei; 
}  
  
.content {  
  width:100%;
  height:280rpx;
  border-radius:16rpx;
  background:#666;
  color:#fff;
  overflow-y: scroll; /*超出父盒子高度可滚动*/  
}  
  
.btn {  
  width: 80%;  
  margin: 45rpx auto 0rpx auto;
  /* 
  display: flex;  
  flex-direction: row;  
  align-items: center;  
  justify-content: space-between;  
  box-sizing: border-box;  
  background-color: white;  
  border-radius:22rpx; */
}  
  
 
  
.Sure {  
  width: 100%;  
  height:90rpx;
  line-height:90rpx; 
  background-color: #666;  
  text-align: center; 
  border-radius:10rpx; 
  color:#fff;
  font-size:40rpx;
  font-weight:bold;
}  
  
.modalMsg {  
  display:block;
  width:80%;
  text-align: left;  
  height:110rpx;
  line-height:110rpx;
  /* margin-top: 45rpx;   */ 
  margin:10rpx auto;
  font-size:48rpx;
  font-weight:bolder;
  letter-spacing:4rpx;
}
           

gameOver.js:

Component({
  properties: {
    modalHidden: {
      type: Boolean,
      value: true
    }, //这里定义了modalHidden属性,属性值可以在组件使用时指定.写法为modal-hidden  
    score: {type: String,value: '30'},
    ranking: { type: String, value: '10' }
  },
  data: {
    // 这里是一些组件内部数据  
    text: "text",
  },
  methods: {
    // 这里放置自定义方法  
    modal_click_Hidden: function () {
      this.setData({
        modalHidden: true,
      })
    },
    // 确定  
    Sure: function () {
      console.log(this.data.text)
    }
  }
})
           

在pages文件下的select中调用该弹框:

在select.wxml中调用

<gameOver modal-hidden="{{is_modal_Hidden}}" />
           

在select.js中增加控制弹框组件的显示:

data:{
   is_modal_Hidden: true,
} 
           

在select.json声明调用组件:

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

显示效果:

微信小程序 - 使用自定义组件