微信小程序--自定义组件(一)简单实现

1创建自定义组件

首先创建一个components文件夹,用于放置所有自定义的组件,创建之后的目录结构为

其中的mycomponent是我们本次要实现组件。

2基本配置

mainpage.json(进行自定义组件声明)

{
  "component": true
}

mainpage.js

Component({  
  options: {  
    multipleSlots: true // 在组件定义时的选项中启用多slot支持  
  },  
  /** 
   * 组件的属性列表 
   */  
  properties: {  
    toastText: {            // 属性名  
      type: String,  
      value: '内容'  
    }  
  },  
  /** 
   * 组件的初始数据 
   */  
  data: {  
    toastShow:false,  
  },  
  /** 
   * 组件的方法列表 
   */  
  methods: {  
    showToast(text,time) {  
      this.setData({  
        toastShow: !this.data.toastShow,  
        toastText: text  
      })  
  
      var that = this  
  
      if (!time){  
        time = 8000  
      }  
  
      setTimeout(function(){  
        that.setData({  
          toastShow: !that.data.toastShow  
        })  
      }, time)  
    }  
  }  
})

toastedit.wxml

<view class='wx_toast_container' hidden="{{!toastShow}}">
  <view class='wx_toast_text'>{{toastText}}</view>
</view>

toastedit.wxss

.wx_toast_container{
    position: fixed; 
    top: 0;
    right: 0;
    left: 0;
    bottom: 0;
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 1000;
}
.wx_toast_text{
    background:rgba(0,0,0,0.95);
    color:white;
    text-align:center;
    font-size:34rpx;
    padding:34rpx 50rpx;
    border-radius:20rpx;
    max-width:70%;
    min-width:35%;
    box-sizing:border-box;
    line-height:120%;
}

3使用组件

在使用组件的index.json中进行声明

    "usingComponents": {  
        "mycomponent": "/components/mycomponent/mainpage"  
    }  
}

在index.wxml中进行组件的引用

<view>
    <mycomponent id="mycomponent">{{toastText}}</mycomponent>     
</view>

index.js

Page({
  onReady: function () {
    //获得toastedit组件
    this.mycomponent= this.selectComponent("#mycomponent")
 
  },
  showToast: function () {
    this.mycomponent.showToast('我是传过来的toast内容',2000)
  }
})

完成。

参考:https://www.jianshu.com/p/34dea82fc312

 

posted @ 2020-09-08 00:39  九零后大辰辰  阅读(190)  评论(0编辑  收藏  举报