微信小程序 自定义组件(modal) 引入组件

时间:2023-12-19 08:28:26

项目结构:

微信小程序 自定义组件(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:'我是一个自定义组件'
}
})

步骤四:效果图

微信小程序 自定义组件(modal) 引入组件