小程序中一个自定义组件由 json wxml wxss js 4个文件组成。
1 创建自定义组件
首先创建一个components文件夹,用于放置所有自定义的组件。
2 基本配置
mytoast.json(进行自定义组件声明)
{
"component": true
}
mytoast.wxml
<view class='wx_toast_container' hidden="{{!toastShow}}">
<view class='wx_toast_text'>{{toastText}}</view>
</view>
mytoast.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%;
}
mytoast.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)
}
}
})
我们要在index.wxml中使用组件的话,首先要在index.json中进行声明
{
"usingComponents": {
"mytoast": "/components/mytoast/mytoast"
}
}
在index.wxml中进行组件的引用
<view>
<mytoast id="toastedit">{{toastText}}</mytoast>
<button type="primary" bindtap="showToast"> showToast! </button>
</view>
index.js的配置
Page({
onReady: function () {
//获得mytoast组件
this.mytoast = this.selectComponent("#mytoast")
},
showToast: function () {
this.mytoast.showToast('我是传过来的toast内容',2000)
}
})