美文网首页
小程序 组件(component)学习

小程序 组件(component)学习

作者: 小屋新 | 来源:发表于2019-05-24 16:40 被阅读0次
一:创建我们的组件文件夹
文件目录
二:把我们需要封装的组件,按类目归好
弹窗组件

弹窗组件根据按钮的不同,分为三类,如上图
下面,重点来了

三:右键新建component

新建component

一定是新建,不是在app.json里面写路径

新建好的component
新建component之后,会出现.js .json .wxml .wxss文件,界面布局和正常文件的界面布局一样
现在,重点来了,介绍一下怎么进行逻辑处理
1、把需要传值的属性放在 properties
properties: {
    // btn按钮标题
    btnTitle: {
      type: String,
      value: 'btn按钮标题'
    },
    // 提示内容
    content: {
      type: String,
      value: '提示内容'
    }
  },

2、把私有属性放在 data 中初始化

data: {
    // 控制界面显示隐藏
    showTips:false
  },

3、把所有要用到的方法放在 methods

methods: {
    hiddenView:function() {
      this.setData({
        showTips:false
      })
    },
    showView:function() {
      this.setData({
        showTips:true
      })
    },
// 外部使用方法,用下划线 _ 区分一下
    _onTap:function() {
      this.triggerEvent('onTap')
    }
  }

此处注意一下,在外部使用的方法最好用 下划线 _ 区分一下

贴一下.wxml的代码吧

<!-- 黑色背景 -->
<view class='tips_container' hidden='{{!showTips}}'>
  <!-- 白色背景框 -->
  <view class='bgWhiteView'>
    <text>{{content}}</text>
    <!-- 顶部背景图片 -->
    <image src='/imgs/tips/icon_tips_bg.png' mode='scaleToFill'>
    </image>
    <!-- 底部按钮 -->
    <button bindtap='_onTap'>{{btnTitle}}</button>
  </view>
</view>

组件中.wxss的代码

.tips_container {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background: rgba(0, 0, 0, 0.5);
  width: 100%;
  height: 100%;
}
.bgWhiteView {
  display: flex;
  flex-direction: column;
  justify-content: center;
  width: 574rpx;
  height: 395rpx;
  border-radius: 10rpx;
  background: #fff;
}
.bgWhiteView image {
  top: 0;
  left: 0;
  width: 100%;
  height: 287rpx;
}
.bgWhiteView text {
  position: absolute;
  vertical-align: middle;
  padding: 0 80rpx 108rpx 80rpx;
  width: 424rpx;
  color: #4a474a;
  font: 36rpx;
}
.bgWhiteView button {
  left: 0;
  bottom: 0;
  width: 100%;
  height: 108rpx;
  background: #fff;
  color: #cbbb90;
}
button::after { 
  border: none; 
}

使用

在.json文件中,需要添加组件路径

"usingComponents": {
    "tips_oneBtn":"/component/tips/tipsOneBtn/tipsOneBtnView"
  }

在.wxml中,对组件传值

<!-- 此标签名需要和 .json 文件中相呼应 -->
<tips_oneBtn 
    id='tips_oneBtn' 
    content='**要获取您的个人信息,您是否允许?' 
    btnTitle='允许' 
    bind:onTap='tipsOneBtnViewTap' 
    wx:if='{{!hasUserInfo && canIUse}}'>
  </tips_oneBtn>

记得在 .wxss中对组件进行布局

#tips_oneBtn {
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
}

在.js中的使用

this.tips_oneBtn = this.selectComponent("#tips_oneBtn")
this.tips_oneBtn.showView()

组件中点击按钮调用的方法

tipsOneBtnViewTap: function() {
    console.log('点击了允许按钮')
  },

新手一枚,哪里不合适可以指出来,耽误了我没事,别耽误了别人😂

相关文章

网友评论

      本文标题:小程序 组件(component)学习

      本文链接:https://www.haomeiwen.com/subject/owrvzqtx.html