微信小程序:封装弹窗组件(含插槽slot的使用)

发布于:2025-07-04 ⋅ 阅读:(14) ⋅ 点赞:(0)

一、基础弹窗样式

1、效果

点击弹窗按钮,出现基础的标题,内容,按钮弹窗

2、主页面代码

(1)WXML

写入按钮,并且使用弹窗组件

  • show:控制弹窗显示与隐藏的变量
  • title:弹窗标题
  • content:弹窗内容
  • bind:close:弹窗关闭方法
  • bind:cancel:弹窗取消方法
  • bind:confirm:弹窗确认方法
<view class="container">
  <button bindtap="showModal">打开弹窗</button>
  <dialog 
    show="{
  {showModal}}" 
    title="自定义标题" 
    content="这是弹窗内容"
    bind:close="hideModal"
    bind:cancel="onCancel"
    bind:confirm="onConfirm"
  ></dialog>
</view>

(2)JS

  • showModal:定义弹窗显示与隐藏变量
  • showModal():触发打开弹窗的方法:如果点击按钮,变量设置为true
  • hideModal():弹窗的隐藏回调事件: bind:close="hideModal"
  • onCancel():弹窗的取消回调事件:bind:cancel="onCancel"
  • onConfirm():弹窗的确认回调事件:bind:confirm="onConfirm"
Page({
  data: {
    showModal: false
  },
  
  showModal() {
    console.log('按钮被点击');
    this.setData({ showModal: true });
  },  
  
  hideModal() {
    this.setData({
      showModal: false
    });
  },
  
  onCancel() {
    console.log('点击了取消');
  },
  
  onConfirm() {
    console.log('点击了确定');
  }
});

(3)JSON

引入弹窗组件,并写入页面基本信息

{
  "usingComponents": {
    "dialog": "/components/dialog/index"
  },
  "navigationBarTitleText": "测试",
  "navigationBarBackgroundColor": "#f5f5f5",
  "navigationBarTextStyle":"black"
}

3、弹窗代码

(1)WXML<


网站公告

今日签到

点亮在社区的每一天
去签到