手机版

Vue实现左右菜单联动

时间:2021-08-30 来源:互联网 编辑:宝哥软件园 浏览:

本文介绍了Vue实现左右菜单联动的代码。分享给大家,给自己留个条,如下:

开源代码库

源代码门户:Rain120/vue-study

之前在外卖软件上看到这个左右联动的效果,觉得很有意思,就尝试用Vue来实现,把这个联动拉开成一个单独的组件。废话少说,从效果图开始。

该组件分为两部分:1 .左侧菜单;2.右菜单。左侧菜单的DOM结构

scroll class=' left-menu ' : data=' left menu ' ref=' left menu ' div class=' left-menu-container ' ul Li class=' left-item ' ref=' left-item ' : class=' { ' curre Nt ' : current index==index } ' @ click='在左菜单中选择left (index,$ event)' v-for=' (item,index)键=' index ' p class=' text ' { item } }/p/Li/

scroll class=' right-menu ' : data=' right menu ' ref=' right menu ' @ scroll height ' : listenslocall=' true ' : probe type=' 3 ' div class=' right-menu-container ' ul Li class=' right-item ' ref=' right item ' v-for='(items,I)在right menu ' 3360 key=' I ' div class=' data-wrapper ' div class=' title ' { items . title }。data ' : key=' j ' { { item } }/div/div/Li/ul/div/scroll这是演示用的,所以数据是简单编造的。

当然,因为这是一个子组件,我们将通过父组件传递道具,所以我们定义道具

prop : { left menu : { required d : true,type: Array,default () { return [] } },right menu : { required d : true,type: Array,default () { return [] } },}

在这个业务场景中,我们的实现是根据右菜单的滚动高度来计算左菜单的位置。当然,左菜单也可以点击,确定右菜单需要滚动多远。那么我们如何得到容器的滚动距离呢?better-卷轴以前用过。通过阅读文档,我们知道它有一个滚动事件,我们可以通过听这个事件来获得滚动位置

如果(这个。让我来。scroll.on ('scroll ',(pos)={me。$ emit ('scroll ',pos)})}所以我们在右侧菜单中的scroll组件上收听scroll事件

@scroll='scrollHeight '方法

scroll height(pos){ console . log(pos);这个。滚动=数学。ABS(数学。圆形(位置。y))},让我们键入从监控中获得的位置

我们可以看到控制台显示的是当前滚动的pos信息,因为在移动终端上开发时坐标轴与我们数学中的坐标轴相反,所以向上滑动时Y轴的值为负

所以我们必须得到每一个李的高度,我们可以得到他们的DOM

_calculateHeight() {让lis=this。$ refs.rightItem让height=0 this . right height . push(height)array . prototype . slice . call(lis)。forEach(Li={ height=Li . client height this . right height . push(height)})console . log(this . right height)}我们调用这个函数来计算创建钩子后的高度

_calculateHeight() {让lis=this。$ refs.rightItem让height=0 this . right height . push(height)array . prototype . slice . call(lis)。forEach(Li={ height=Li . client height this . right height . push(height)})console . log(this . right height)}

当用户滚动时,我们需要计算当前的滚动距离在该区间内,并获得他的索引

computed : { current index(){ const { scrollY,rightHeight }=此const index=right height . find index((height,index)={ return scrollY=right height[index]scrollY right height[index 1]})返回索引0?索引: { 0 } }因此,它应该是左侧菜单索引=1的活动菜单项。以上是左菜单按右菜单滑动联动的实现。用户也可以点击左侧菜单,实现右侧菜单的联动。此时,我们向菜单项添加click事件。

@ click=' select left (index,$event)'在此添加$ event以区分本机click事件和[better-scroll]((https://ustbhangyi . github . io/better-scroll/doc/zh-Hans/# better-scroll)

选择左(索引,事件){ if(!事件。_ construct){ return }让右项=this。参考文献。右项让El=右项[索引]这个。参考文献。右菜单。scrolltoelement (El,300)},我们在这里基本完成了这些需求

以上就是本文的全部内容。希望对大家的学习有帮助,支持我们。

版权声明:Vue实现左右菜单联动是由宝哥软件园云端程序自动收集整理而来。如果本文侵犯了你的权益,请联系本站底部QQ或者邮箱删除。