1. 创建弹窗组件
WXML
{{title}} {{content}}
WXSS
/* components/popup/popup.wxss */ .popup { position: fixed; left: 0; top: 0; width: 100%; height: 100%; display: flex; align-items: center; justify-content: center; z-index: 999; } .popup-overlay { position: absolute; left: 0; top: 0; width: 100%; height: 100%; background: rgba(0, 0, 0, 0.5); } .popup-content { position: relative; width: 80%; max-width: 300px; background: white; border-radius: 8px; overflow: hidden; } .popup-header { display: flex; justify-content: space-between; align-items: center; padding: 16px; background: #f7f7f7; } .popup-title { font-size: 18px; font-weight: bold; } .popup-close { background: none; border: none; font-size: 24px; color: #333; } .popup-body { padding: 16px; } .popup-footer { padding: 16px; text-align: right; } .popup-button { background: #1aad19; color: white; border: none; padding: 8px 16px; border-radius: 4px; }
JS
// components/popup/popup.js Component({ properties: { visible: { type: Boolean, value: false }, title: { type: String, value: '弹窗标题' }, content: { type: String, value: '弹窗内容' } }, methods: { closePopup() { this.triggerEvent('close'); }, onConfirm() { this.triggerEvent('confirm'); } } });
JSON文件
{ "component": true, "usingComponents": {} }
2. 在页面中使用弹窗组件
在 pages/index/index.wxml 文件中添加弹窗组件并实现按钮点击事件:
在 pages/index/index.wxss 文件中定义页面样式:
/* pages/index/index.wxss */ .container { display: flex; flex-direction: column; align-items: center; justify-content: center; height: 100vh; }
在 pages/index/index.js 文件中实现弹窗显示和页面跳转:
// pages/index/index.js Page({ data: { showPopupDialog: false }, // 显示弹窗 showPopup() { this.setData({ showPopupDialog: true }); }, // 关闭弹窗 onPopupClose() { this.setData({ showPopupDialog: false }); }, // 确认按钮点击 onPopupConfirm() { this.setData({ showPopupDialog: false }); // 页面跳转 wx.navigateTo({ url: '/pages/target/target' // 目标页面路径 }); } });