uniapp索引菜单组件

本文介绍了一种方法,通过在Vue组件里利用scroll-view的scroll-into-view属性和uni.createSelectorQuery().selectAll监听,实现点击侧边索引时页面内容滚动到相应位置的功能。代码示例展示了如何绑定滚动事件,以及处理索引栏的激活状态。
摘要由CSDN通过智能技术生成

官方提供了监听页面滚动事件控制索引跳转,但是一旦封装了组件就无法实现监听效果,本文基于scroll-view的scroll-into-view属性实现点击索引跳转;通过

 uni .createSelectorQuery().selectAll监听实现滚动标记

废话不多说直接上代码

<template>

  <view>

    <!-- 滚动内容 -->

    <scroll-view class="home" :scroll-y="true" :scroll-into-view="intoViewId" scroll-with-animation @scroll="scroll">

        <!-- 循环索引栏 -->

      <view v-for="(item, index) in indexList" :key="index" :id="'i' + index" class="indexItem">

        <text>{{ item }}</text>

        <!-- 根据索引栏id查找显示内容 -->

        <view class="itemArr" v-for="(v, i) in itemArr[index]" :key="i">

          {{ v }}

        </view>

      </view>

    </scroll-view>

    <!-- 侧边索引栏 -->

    <view class="indexList">

      <view

        :class="{ isActive: activeId === `i${index}` }"

        v-for="(item, index) in indexList"

        @click="toID(index)"

        :key="index">

        {{ item }}

      </view>

    </view>

  </view>

</template>

<script>

export default {

  data() {

    return {

      intoViewId: null,

      activeId: "i0",

      indexList: ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J"],

      itemArr: [

        ["列表A1", "列表A2", "列表A3"],

        ["列表B1", "列表B2", "列表B3"],

        ["列表C1", "列表C2", "列表C3"],

        ["列表D1", "列表D2", "列表D3"],

        ["列表E1", "列表E2", "列表E3"],

        ["列表F1", "列表F2", "列表F3"],

        ["列表G1", "列表G2", "列表G3"],

        ["列表H1", "列表H2", "列表H3"],

        ["列表I1", "列表I2", "列表I3"],

        ["列表J1", "列表J2", "列表J3"],

      ],

    };

  },

  methods: {

    toID(index) {

      console.log(123);

      const id = "i" + index;

      console.log(id);

      this.intoViewId = id;

    },

    indexClick(e) {

      console.log(e);

    },

    scroll(e) {

      //获取scroll-view中展示的元素

      uni

        .createSelectorQuery()

        .selectAll(".indexItem")

        .boundingClientRect((data) => {

          const showArr = data.filter((item) => {

            return item.top >= 0;

          });

          //获取第一个元素的id

          const id = showArr[0].id;

          console.log(id);

          //设置选中的id

          this.activeId = id;

        })

        .exec();

    },

  },

};

</script>

<style lang="scss" scoped>

.indexList {

  display: flex;

  flex-direction: column;

  width: 20px;

  background-color: #eee;

  position: fixed;

  top: 50px;

  right: 20px;

  align-items: center;

}

.home {

  height: 300px;

}

.itemArr {

  margin: 30px auto;

}

.isActive {

  color: rgb(28, 163, 204);

}

</style>

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值