小程序自定义TabBar后如何实现keep-alive
发布于 3 年前 作者 kliao 2046 次浏览 来自 分享

小程序自定义TabBar后如何实现keep-alive

前段时间写了小程序实现TabBar创意动画小程序开发技巧后,有小伙伴提问到,自定义TabBar是可以做很多交互,但点击切换TabBar页面,都会伴随着组件的销毁和重建,这点确实会影响性能。这里就提供一个方案来实现“keep-alive”。如有更好的方案,欢迎评论区交流。欢迎点赞和收藏~

自定义TabBar方案

虽然在之前文章提到过了,本次采用组件化实现

我们可以新建一个`` home ``文件夹,在`` home/index.wxml ``中写一个__tabBar__,然后把`` TabBar ``页面写成组件,然后点击__TabBar__切换相应的组件展示就可以。代码如下:
wxml部分
<!-- home页面 -->

<view id='index'>
  <!-- 自定义头部 -->
  <head name='{{name}}' bgshow="{{bgshow}}" backShow='false'></head>

    <!-- 首页 -->
    <index change='{{activeIndex==0}}'></index>
    <!-- 购物车 -->
    <cart change='{{activeIndex==1}}'></cart>
     <!-- 订单 -->
    <order change='{{activeIndex==2}}'></order>
    <!-- 我的 -->
    <my change='{{activeIndex==2}}'></my>
    <!-- tabbar -->
    <view class="tab ios">
        <view class="items {{activeIndex==index?'active':''}}" wx:for="{{tab}}" bindtap="choose" data-index='{{index}}' wx:key='index' wx:for-item="items">
            <image wx:if="{{activeIndex==index}}" src="{{items.activeImage}}"></image>
            <image wx:else src="{{items.image}}"></image>
            <text>{{items.name}}</text>
        </view>
    </view>
</view>

  • home页面的ts
Page({
  data: {
    activeIndex:0,
    tab:[
      {
        name:'商品',
        image:'../../images/index.png',
        activeImage:'../../images/index-hover.png',
      },
      {
        name:'购物车',
        image:'../../images/cart.png',
        activeImage:'../../images/cart-hover.png',
      },
      {
        name:'订单',
        image:'../../images/order.png',
        activeImage:'../../images/order-hover.png',
      },
      {
        name:'我的',
        image:'../../images/my.png',
        activeImage:'../../images/my-hover.png',
      }
    ]
  },
  // 切换事件
  choose(e:any){
    const _this=this;
    const {activeIndex}=_this.data;
    if(e.currentTarget.dataset.index==activeIndex){
      return
    }else{
        _this.setData({
          activeIndex:e.currentTarget.dataset.index
        })
    }
  },
})

  • 上面代码不难理解,点击以后改变activeIndex从而控制每个组件的渲染和销毁,这样付出的代价还是比较大的,需要我们进一步的优化。

如何实现keep-alive

我们知道,这里主要是避免组件反复创建和渲染,有效提升系统性能。

实现思路

1.在`` tab ``每个选项增加两个值:`` status ``和`` show ``,`` show ``控制组件是否需要渲染,`` status ``控制组件`` display ``
2.初始化时候设置首页的`` status ``和`` show ``,其他都为`` false ``
3.当我们切换时:把上一个`` tab ``页面的`` status ``改为`` false ``,然后把当前要切换页面的`` tab ``数据中的`` status ``和`` show ``都改为`` true ``,最后再更新一下`` activeIndex ``的值。
wxml代码:
    <!-- 首页 -->
    <view wx:if="{{tab[0].show}}" hidden="{{!tab[0].status}}">
        <index></index>
    </view>
    <!-- 购物车 -->
    <view wx:if="{{tab[1].show}}"  hidden="{{!tab[1].status}}">
        <cart></cart>
    </view>
    <!-- 订单 -->
    <view wx:if="{{tab[2].show}}" hidden="{{!tab[2].status}}">
         <order></order>
    </view>
    <!-- 我的 -->
    <view wx:if="{{tab[3].show}}" hidden="{{!tab[3].status}}">
        <my></my>
    </view>
  • ts代码
Page({
  data: {
    activeIndex:0, //当前选中的index
    tab:[
      {
        name:'商品',
        image:'../../images/index.png',
        activeImage:'../../images/index-hover.png',
        status:true,//控制组件的display
        show:true, //控制组件是否被渲染
      },
      {
        name:'购物车',
        image:'../../images/cart.png',
        activeImage:'../../images/cart-hover.png',
        status:false,
        show:false,
      },
      {
        name:'订单',
        image:'../../images/order.png',
        activeImage:'../../images/order-hover.png',
        status:false,
        show:false,
      },
      {
        name:'我的',
        image:'../../images/my.png',
        activeImage:'../../images/my-hover.png',
        status:false,
        show:false,
      }
    ]
  },
  
  choose(e:any){
    const _this=this;
    const {activeIndex}=_this.data;
    //如果点击的选项是当前选中,就不执行
    if(e.currentTarget.dataset.index==activeIndex){
      return
    }else{
       //修改上一个tab页面的status
       let prev='tab['+activeIndex+'].status',
           //修改当前选中元素的status
           status='tab['+e.currentTarget.dataset.index+'].status',
           //修改当前选中元素的show
           show='tab['+e.currentTarget.dataset.index+'].show';
      
        _this.setData({
          [prev]:false,
          [status]:true,
          [show]:true,
          activeIndex:e.currentTarget.dataset.index,//更新activeIndex
        })
    }
  },

})

  • 这样基本就大功告成了,来看一下效果:

  • 当我们点击切换时候,如果当前组件没有渲染就会进行渲染,如果渲染过后进行切换只是改变display,完美实现了需求,大功告成!

实际业务场景分析

在实际使用中还有两种种情况:
情况1:比如某些数据并不希望他首次加载后就数据保持不变,当切换页面时候希望数据进行更新,比如笔者做的电商小程序,在首页点击商品加入购物车,然后切换到购物车,每次切换时候肯定需要再次进行请求。
情况2:像个人中心这种页面,数据基本请求一次就可以,没必要每次切换请求数据,这种我们不需要进行改进。

我们给组件传递一个值:`` status ``,然后在组件中监听这个值的变化,当值为`` true ``时候,去请求接口更新数据。具体代码如下:
wxml代码(只列举关键部分):
<!-- 首页 -->
 <view wx:if="{{tab[0].show}}" hidden="{{!tab[0].status}}">
    <index change='{{tab[0].status}}'></index>
 </view>

<!-- 购物车 -->
 <view wx:if="{{tab[1].show}}"  hidden="{{!tab[1].status}}">
  <cart change='{{tab[0].status}}'></cart>
 </view>
  • 首页组件/购物车组件ts代码:
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    change: {
      type: String,//类型
      value: ''//默认值
    },
  },
  observers: {
    //监听数据改变进行某种操作
    'change': function(change) {
      if(change=='true'){
        console.log('更新首页数据'+change)
      }
    }
  },
})
  • 来看一下最终效果:

结尾

目前能想到的实现方法就是这样,如果你有更好的方法,欢迎评论区交流,文章如有错误问题欢迎指正。

1 回复

你这样的话 每个页面就要写成一个component了对吧?相当于自己完成了一套router。这样就是为了解决tab问题而带来了新的麻烦。如果用官方的自定义tabbar的功能就能避免tabbar组件每次重新渲染的问题。

https://developers.weixin.qq.com/miniprogram/dev/framework/ability/custom-tabbar.html

回到顶部