微信小程序 分類菜單激活狀態跟隨列表滾動切換 mpvue

效果圖

實現/原理

  • 點擊分類,滾動到列表對應位置。

    用上了< scroll-view >這個組件,包括滾動時的事件,點擊分類列表跳轉到對應的位置,滾動的動畫等html

  • 滑動列表到對應範圍,對應分類展現激活狀態。

    這個本來覺得是比較麻煩的部分,其實很簡單。小程序

    用上了wx.createSelectorQuery()這個api,直接獲取每一個分類列表的高度,頂部位置等。微信小程序

    咱們就能夠根據每一個分類距離頂部的位置來判斷是不是激活的分類。

    注意滾動列表的變量跟激活菜單的變量應該是不公用的api

部分代碼

html部分

//左邊分類
  <scroll-view scroll-y class="ser-menu">
      <div
        v-for="(item,index) in productlist"
        :key="index"
        :class="{'active':activeClassifyListId==item.classifyId}"
        @click="activeClassify(item.classifyId)"
        class="nemeitem"
        v-if="item.list.length>0"
      >
        <text class="title">{{item.classifyName}}</text>
      </div>
    </scroll-view>
複製代碼
//右邊列表
  <scroll-view
    scroll-y
    class="list"
    :scroll-into-view="'item'+activeClassifyId"
    scroll-with-animation
    @scroll="scroll"
  >
      
    <div
      class="listBox"
      :class="'list'+product.classifyId"
      :id="'item'+product.classifyId"
      v-for="(product,productIndex) in productlist"
      :key="productIndex"
      v-if="product.list.length>0"
    >
    //......省略部分代碼
    </div>
   </scroll-view>
複製代碼

js部分

// 滾動右邊列表
   scroll(){
     this.productlist.map(item=>{
       if(item.list.length>0){
      const query = wx.createSelectorQuery()
       query.select('.list'+item.classifyId)
       .boundingClientRect(reft=>{
         if(0>reft.top&&reft.top>(reft.height*-1)){
           this.activeClassifyIds = item.classifyId
         }
       }).exec()
       }
     })
   },
複製代碼

微信小程序封裝的組件和api真是愈來愈順手的啊!哈哈

相關文章
相關標籤/搜索