(四)小程序案例-tab栏切换——数据在js文件中操作,通过修改数据动态改变页面样式

案例

  • Tab案例基本布局

在这里插入图片描述

<!-- Tab案例实践 -->
<view class='tab'>
  <view class='title'>
    <view class='tab-title'>js高程</view>
    <view class='tab-title'>明朝那些事</view>
    <view class='tab-title'>浪潮之巅</view>
  </view>
  <view class='tab-content active'>js系统性语法</view>
  <view class='tab-content'>以故事的方式结合幽默诙谐的语言风格描述了明朝数百年的历史</view>
  <view class='tab-content'>科技巨头的兴衰史</view>
</view>
  • 业务逻辑实现
  handleChange: function(e) {
    // 处理Tab切换操作:控制currentIndex的变化
    let i = e.target.dataset.index
    // 修改currentIndex的值
    this.setData({
      currentIndex: parseInt(i)
    })
  },
<!-- Tab案例实践 -->
<view class='tab'>
  <view bind:tap='handleChange' class='title'>
    <view data-index='1' class='tab-title {{currentIndex===1?"current":""}}'>js高程</view>
    <view data-index='2' class='tab-title {{currentIndex===2?"current":""}}'>明朝那些事</view>
    <view data-index='3' class='tab-title {{currentIndex===3?"current":""}}'>浪潮之巅</view>
  </view>
  <view class='tab-content {{currentIndex===1?"active":""}}'>js系统性语法</view>
  <view class='tab-content {{currentIndex===2?"active":""}}'>以故事的方式结合幽默诙谐的语言风格描述了明朝数百年的历史</view>
  <view class='tab-content {{currentIndex===3?"active":""}}'>科技巨头的兴衰史</view>
</view>
  • 代码优化-数据在js文件中操作,通过修改数据动态改变页面样式
<!-- Tab案例实践 -->
<view class='tab'>
  <view bind:tap='handleChange' class='title'>
    <view wx:key='{{item.id}}' wx:for='{{tabData}}' data-index='{{item.id}}' class='tab-title {{currentIndex===item.id?"current":""}}'>{{item.title}}</view>
  </view>
  <view wx:key='{{item.id}}' wx:for='{{tabData}}' class='tab-content {{currentIndex===item.id?"active":""}}'>{{item.content}}</view>
</view>
  onLoad: function (options) {
    // console.log('onLoad')
    // 这里一般用于初始化数据
    var data = [{
      id: 1,
      title: '三国演义',
      content: '一个军阀混战的年代'
    }, {
      id: 2,
      title: '红楼梦',
      content: '一个封建贵族生活的缩影'
    }, {
      id: 3,
      title: '西游记',
      content: '佛教和道教的斗争'
    }, {
      id: 4,
      title: '水浒传',
      content: '草寇是斗不过正规军的'
    }];
    this.setData({
      tabData: data
    })
  },
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值