微信小程序分类的实现

微信小程序的分类功能思路

在这里插入图片描述

实现思路

1.把屏幕当成一个固定的盒子,然后把盒子分成两边,并让盒子的每一边都能够滚动。
2.通过将左侧边栏元素的id和右边内容的categoryId进行匹配,渲染展示相同id的内容

页面data定义的初始数据

 /**
   * 页面的初始数据
   */
 data: {
    classify_sidebar: [], //左侧边栏内容的数组
    classify_content: [],  //右边内容元素的数组
    list: 124849,  //绑定切换时的id
  },

 

1.先利用文档对左边的侧边栏进行布局和渲染


<!-- 左侧边栏 -->
<scroll-view class="left"  scroll-y="true">
<view class="classify_sidebar">
<view class="{{item.id===list?'classify_active':''}}" 
data-id="{{item.id}}" 
catchtap="change" 
wx:for='{{classify_sidebar}}'   
wx:key="index">{{item.name}}</view>
</view>    
</scroll-view>

 


 class="{{item.id===list?'classify_active':''}}"  
 运用三目运算符来给当前选中的元素切换样式(红色下划线),如果说当前元素的id和我们设置的list相同就添加类名加样式

 

data-id="{{item.id}}"  通过自定义来传参,根据左侧边栏元素的id来匹配右边的内容 
catchtap="change" 
当用户点击不同的侧边栏目录时候,根据 data-id 去从数据库获取新的数据,
渲染到左侧,并且修改 list的值,使新样式添加到点击的元素上

change(e) {
    let {id} = e.currentTarget.dataset
    this.contentFn(id) //封装的方法
    this.setData({
      list: id
    })
    wx.showLoading({
      title: '加载中',
    })
    setTimeout(() => {
      wx.hideLoading()
    }, 1000)
  },

 


2.右边内容的布局和渲染


<scroll-view  class="right" scroll-y="true">
<!-- 右边的内容部分 -->
<view class="classify_content">
<!-- 右边内容的列表 -->
<text wx:if="{{classify_content.length == 0}}">—————  暂无数据  ————</text>

<view class="classify_content_list" wx:if="{{classify_content.length > 0}}" wx:for="{{classify_content}}" wx:key="index">
<!-- 右边内容的列表图片 -->
<image src="{{item.pic}}"></image>
<text class="classify_content_list_right_title">{{item.name}}</text>
</view>
<!-- 右边内容的列表结束 -->
</view>
<!-- 右边的内容部分结束 -->
</scroll-view>
wx:if="{{classify_content.length == 0}}">

 


如果说右边相对应的商品数量为零就显示 “暂无数据”

 


//  封装
  contentFn(tar) {
    let arr = []
    wx.request({
      url: 'https://api.it120.cc/lsn/shop/goods/list',
      success: res => {
        if (res.statusCode == 200) {
          res.data.data.forEach((item, v) => {
            if (item.categoryId == tar) {
              arr.push(item)
            }
          })
          this.data.classify_content = arr.reverse()
          this.setData({
            classify_content: this.data.classify_content
          })
        }
      }
    })
  },

思路
首先封装个方法然后在点击切换左侧边栏的时候进行调用
第一步:通过wx.request()去请求右边所有内容
第二步:如果说状态码200表示“服务器成功返回网页”
第三步:通过循环右边的内容,如果说当前categoryId等同于我们点击左侧边栏的id,数组push添加,同时倒序并且赋值给我们自己定义的数组和进行试图更新

posted @ 2020-10-22 08:55  晚风还会晚嗎  阅读(2339)  评论(0编辑  收藏  举报