小程序点击分类自动滚动到分类的第一个商品

27 阅读1分钟

产品列表对象是一个多维数组

const products = reactive([
   {
    categoryId: 1,
    categoryName: '分类1',
    items: [
      { id: 1, name: '商品名称A', price: '¥88', desc: '商品说明A' },
      { id: 2, name: '商品名称B', price: '¥128', desc: '商品说明B' }
    ]
  },
  {
    categoryId: 2,
    categoryName: '分类2',
    items: [
      { id: 1, name: '商品名称C', price: '¥56', desc: '商品说明C' },
      { id: 2, name: '商品名称D', price: '¥99', desc: '商品说明D' }
    ]
  }
])

scroll-into-view来设置需要滚动到的位置

通过双重for循环来设置每一个分类唯一的id

 <scroll-view scroll-y  class="productList" :scroll-into-view="currentCategoryId">
      <view v-for="category in products" :key="category.categoryId" >
        <view 
          v-for="p in category.items" 
          :key="p.id"  
          class="product-item"  
          :id="'category-' + category.categoryId + '-item-' + p.id" 
          @tap="viewProduct(p)"
        >
          
          <text class="text-3_158">{{ p.name }}</text>
          <text class="text-3_159">{{ p.price }}</text>
         
        </view>
      </view> 
  </scroll-view>

设置的需要滚动到的位置是currentCategoryId,然后再利用javascript去动态设置他的值

这里传入的name是我点击的对应的分类标签。循环遍历我一层数组,当命名标签和我的一层数组当中的categoryName一样的时候,就定义这个currentCategoryId为相应的分类的第一个产品的id。

const currentCategoryId = ref('')
const selectCategory = (name) => {
  categoryType.value = name
  for(const cat of products){
    if(name === cat.categoryName){
      currentCategoryId.value = `category-${cat.categoryId}-item-${cat.items[0].id}`
    }
  }