微信小程序:实现单页面内的翻页功能-实现代码

时间:2024-12-12 22:15:53

wxml

通过if去判断是哪个页面

<view wx:if="{{ currentPage == 'page1' }}">
  页面1
  <!-- 按钮 -->
  <view class="Btn_layout">
    <view class="Btn1">
      <view bindtap="submitForm" class="Btn_op" bindtap="nextPage">下一页</view>
    </view>
  </view>
</view>
<view wx:if="{{ currentPage == 'page2' }}">
  页面2
  <!-- 按钮 -->
  <view class="Btn_layout">
    <view class="Btn">
      <view bindtap="submitForm" class="Btn_op" bindtap="previousPage">上一页</view>
      <view bindtap="submitForm" class="Btn_op" bindtap="nextPage">下一页</view>
    </view>
  </view>
</view>
<view wx:if="{{ currentPage == 'page3' }}">
  页面3
  <!-- 按钮 -->
  <view class="Btn_layout">
    <view class="Btn1">
      <view bindtap="submitForm" class="Btn_op" bindtap="previousPage">上一页</view>
    </view>
  </view>
</view>

wxss

只写了按钮的样式

/* 提交按钮 */
.Btn_layout {
  padding: 8% 0;
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

/* 按钮 */
.Btn {
  width: 95%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  z-index: 1000;
}

.Btn1 {
  width: 95%;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  z-index: 1000;
}

.Btn_op {
  width: 48%;
  height: 32px;
  display: flex;
  justify-content: center;
  align-items: center;
  border-top: 2px solid #4472c4;
  background-color: #4472c4;
  color: #fff;
  letter-spacing: 2px;
  border-radius: 5px;
}

js

Page({
  data: {
    currentPage: 'page1', //默认第一页
  },
  // 上一页的事件处理函数
  previousPage: function() {
    let currentPage = this.data.currentPage;
    let pageIndex = parseInt(currentPage.replace('page', ''));
    if (pageIndex > 1) {
      pageIndex--;
      this.setData({ currentPage: `page${pageIndex}` });
    }
  },
  // 下一页的事件处理函数
  nextPage: function() {
    let currentPage = this.data.currentPage;
    let pageIndex = parseInt(currentPage.replace('page', ''));
    // 假设最大页面数为3
    if (pageIndex < 3) {
      pageIndex++;
      this.setData({ currentPage: `page${pageIndex}` });
    }
  }, 
})