左侧导航栏分类 ---联动版本

在uni-app中实现左侧导航栏与右侧内容的联动效果,主要涉及两个部分:左侧的导航栏(通常为垂直列表)和右侧的内容区域。当用户点击左侧某个分类时,右侧的内容区域应滚动到相应的位置;同时,当右侧内容滚动时,左侧的导航栏也应相应地显示当前的活动分类。

以下是一个基本的实现思路:

1. 数据结构

首先,你需要定义一个数组来保存分类和对应内容的数据。例如:

 
 
const categories = [
  { id: 'cat1', name: '分类1', items: [...] },
  { id: 'cat2', name: '分类2', items: [...] },
  // ... 其他分类
];

2. 页面布局

页面可分为左侧的导航栏和右侧的内容区域。

 
 
<template>
  <view class="container">
    <view class="sidebar">
      <view v-for="(category, index) in categories" :key="category.id" @click="selectCategory(index)">
        {
   
   { category.name }}
      </view>
    </view>
    <scroll-view class="content" scroll-y="true" :scroll-into-view="currentId">
      <view v-for="category in categories" :id="category.id" :key="category.id">
        <!-- 这里是每个分类的内容 -->
      </view>
    </scroll-view>
  </view>
</template>

3. 样式

对左侧导航栏和右侧内容区域进行基本的样式设置。

 
 
<style>
.container {
  display: flex;
}
.sidebar {
  width: 20%; /* 或根据需求调整 */
  /* 其他样式 */
}
.content {
  width: 80%; /* 或根据需求调整 */
  /* 其他样式 */
}
</style>

4. 方法实现

实现点击左侧分类,右侧内容滚动到相应位置的功能。

 
 
<script>
export default {
  data() {
    return {
      categories: [...], // 分类数据
      currentId: '' // 当前选中的分类ID
    };
  },
  methods: {
    selectCategory(index) {
      this.currentId = this.categories[index].id;
    }
  }
};
</script>

5. 右侧内容滚动监听(可选)

如果还需要实现当右侧内容滚动时,左侧导航栏自动高亮当前分类的功能,你可以添加滚动监听并计算当前活动的分类。

 
 
<scroll-view class="content" scroll-y="true" :scroll-into-view="currentId" @scroll="handleScroll">
  <!-- 内容 -->
</scroll-view>

handleScroll 方法中,根据滚动的位置判断当前活动的分类,并更新 currentId

这只是一个基本实现思路,具体的代码可能需要根据你的具体需求和项目结构进行调整。在实际开发中,还可能需要处理一些细节,比如分类内容高度不一、滚动性能优化等问题。

猜你喜欢

转载自blog.csdn.net/A12536365214/article/details/134905749