微信小程序实现抽屉Drawer从下方弹出

TDesign中的Drawer方向只能设置为左右,于是自己写一个:

新建component:drawer

drawer.json:

{
  "component": true
}

drawer.wxml


  
  

  
  
    
      {{title}}
    
    
      
    
  

drawer.wxss

.container {
  position: relative;
  padding: 0;
}

/* 遮罩层样式 */
.overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 10;
}

/* 抽屉样式 */
.drawer {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: white;
  z-index: 20;
  box-shadow: 0px -4px 10px rgba(0, 0, 0, 0.2);
  border-top: 1px solid #ddd;
  max-height: 60%;  /* 默认最大高度 */
  padding: 20px;
  box-sizing: border-box;
  transform: translateY(100%);  /* 初始状态隐藏 */
}

/* 抽屉头部 */
.drawer-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

/* 抽屉内容 */
.drawer-body {
  margin-top: 20px;
  font-size: 16px;
}

drawer.js

Component({
  properties: {
    title: {
      type: String,
      value: ""
    }
  },
  data: {
    visible: false,
    animationData: {}  // 动画数据
  },
  methods: {
    // 打开抽屉
    openDrawer() {
      this.setData({ visible: true });
      this.slideUp();  // 执行从底部弹出的动画
    },

    // 关闭抽屉
    closeDrawer() {
      this.slideDown();  // 执行收回的动画
    },

    // 从底部滑动动画
    slideUp() {
      const animation = wx.createAnimation({
        duration: 300,
        timingFunction: 'ease-in-out',
      });
      this.animation = animation;
      animation.translateY(0).step();
      this.setData({
        animationData: animation.export(),
      });
    },

    // 收回动画
    slideDown() {
      const animation = wx.createAnimation({
        duration: 300,
        timingFunction: 'ease-in-out',
      });
      this.animation = animation;
      animation.translateY('100%').step();
      this.setData({
        animationData: animation.export(),
      });

      // 动画结束后隐藏抽屉
      setTimeout(() => {
        this.setData({ visible: false });
      }, 300);  // 等待动画结束再隐藏
    }
  }

});

使用Drawer

.json

{
  "usingComponents": {
    "drawer": "/components/drawer/drawer"
  }
}

.wxml




  content

.js

// pages/workbench/workbench.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    drawer: null
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // 获取抽屉子组件
    this.drawer = this.selectComponent("#drawer")
  },

  drawerShow() {
    if (this.drawer) {
      this.drawer.openDrawer();
    }
  }
})

效果:

微信小程序实现抽屉Drawer从下方弹出_第1张图片

你可能感兴趣的:(微信小程序,小程序)