当前位置: 首页 > news >正文

Vue3:横向滑动导航组件路由跳转保留滚动(条)量

导航组件,点击路由跳转到相应路由,保留当前滚动条的滚动量(滚动条位置)。通过导航宽度计算进行滚动条偏移量移动,无需缓存、存储及路由守卫等。

效果:

navigation.vue(导航组件) 

<template>
<div class="nav f18 lh56">
<ul ref="scrollContainer">
<li v-for="(nav,index) in navData" :key="index" @click="goUrl(nav.url)" :class="{active:url==nav.url}">{{nav.name}}</li>
</ul>
</div>
</template>
<script setup>
import { defineComponent, getCurrentInstance, ref, reactive, computed, onMounted, onActivated, onDeactivated,watch} from 'vue';
import { useRoute } from 'vue-router';
const route = useRoute();
const { proxy } = getCurrentInstance()//导航数据
const navData = [{name:"首页-公告资讯",url:"/index"},{name:"课程中心",url:"/courseCenter"},{name:"新销售员培训",url:"/hireTraining"},{name:"已收藏课程",url:"/collectCourse"},{name:"大咖来支招",url:"/tycoonCounsel"},{name:"学习排行榜",url:"/studyRank"},{name:"培训证书",url:"/TrainingCertificate"},
]//检测路由变换添加样式
let url = ref()
if(route.path){url.value = route.path
}else{url.value = navData[0].url
}//点击跳转
const goUrl = (event) =>{proxy.$router.push(event)
}let scrollContainer = ref(null) //获取导航元素
onMounted(() => {//获取导航条长度(注:.nav ul设置了overflow-x:auto)并根据路由地址滚动到相应位置for(let i in navData){if(route.path == navData[i].url){scrollContainer.value.scrollLeft = i*(scrollContainer.value.scrollWidth/navData.length)}}
})
</script><style scoped>
.nav{background:#2573e9;}
.nav ul{display:flex;justify-content:space-between;}
.nav li{flex:1;text-align:center;color:#fff;cursor:pointer;}
.nav li.active,.nav li:hover{background:#0249b8;}
@media screen and (max-width:860px) {
.nav{line-height:3.4rem;font-size:1.4rem;}
.nav ul{width:100%;white-space:nowrap;display:block;overflow-x:auto;}
.nav ul::-webkit-scrollbar{width:0;height:0;}
.nav ul li{display:inline-block;padding:0 1rem;}
}
</style>

引用:

<template>
<div><!--其他代码--><navigation></navigation><!--其他代码--></div>
</template>
<script setup>
import { defineComponent, getCurrentInstance, ref, reactive, computed, onMounted, onActivated, onDeactivated} from 'vue';//引用导航组件navigation.vue
import navigation from '@/components/navigation.vue'//其他代码</script>
<style scoped>
</style>


http://www.mrgr.cn/news/57719.html

相关文章:

  • 【Java数据结构】---Map和Set(二叉搜索树)
  • python元组应用案例实践(取极值与排序)
  • douyin uid转sec_uid 各种进行转换
  • MySQL启动报错:InnoDB: Unable to lock ./ibdata1 error
  • 计算机网络(十二) —— 高级IO
  • 工业一体机为软件开发商提供稳定可靠的硬件平台
  • HKC双模显示器评测报告 - HKC G27H7Pro
  • 1688API商品详情接口如何获取
  • 解锁PDF权限密码
  • 腾讯地图SDK 手势失效或冲突的解决办法
  • 没有基础,学习HCIE难吗?
  • 【多商户商城适用于哪些行业】
  • (北京餐饮满意度调查公司)餐饮企业顾客满意度调查,赢得口碑的关键
  • Selenium 流程自动化
  • 简单解析WebAPI与WebService的区别
  • 数据连接池的工作机制
  • 无线领夹麦克风怎么挑选,麦克风行业常见踩坑点,避雷不专业产品
  • HarmonyOS 鸿蒙面试第一弹
  • NumPy(by千锋教育)
  • 无废话、光速上手 React-Router
  • ORA-12170: TNS: 连接超时,oracle透过防火墙windows设置USE_SHARED_SOCKET=TRUE
  • 牛客网热度最高的17套一线大厂Java面试八股文!面面俱到,太全了
  • 国家眼部疾病临床病例集《眼视光案例荟》首刊在三亚隆重发布
  • 070_基于springboot的Q高中素质评价档案系统
  • Three.js 使用着色器 实现跳动的心
  • 2D拓扑图