uniapp如何实现tab切换线条跟随效果

uniapp如何实现tab切换线条跟随效果
效果展示

tab切换我们经常使用,那如何去实现一个上面的效果呢,本文将解释一下在uniapp中如何实现

原理解析

uniapp如何实现tab切换线条跟随效果
结构剖析

如上图
红色框框代表盒子,总宽度记作W
绿色框框代表每一项,宽度记作I
深蓝色框框代表的是线,宽度记作C

那么我们可以得到线的左边距每一项的左边距加上一个值
这个值每一项的宽度减去线的宽度结果除以二
I.left + (I.width – C.width) / 2

获取每一项的信息

这里我们就要用到uni查询节点的api,可以拿到节点的信息

const query = uni.createSelectorQuery()
// name 是class 或者 ID
query.select(name).boundingClientRect(data => {
  // data就是节点信息
}).exec();

实操

这里使用的Vue3语法,前面重要的两个知识已经知道了,下面就可以你直接实现了

<template>
 <view class="tabs_wrap">
  <view :class="['item','item' + (index + 1)]" @tap="changeIndex(index)" v-for="(item,index) in tabsList"
   :key="index">

   {{ item.name  || ""}}
  </view>
  <view class="active" :style="{left:left + 'px'}"></view>
 </view>
</template>

<script setup>
 import {
  onMounted,
  getCurrentInstance,
  ref
 } from "vue"

 const query = ref(null)
 const left = ref(0)
  const current = ref(0)
  const tabsList = [{
   name"热榜",
   value""
  },
  {
   name"热点",
   value""
  },
  {
   name"热门收藏夹",
   value""
  }
 ]

 onMounted(() => {
  query.value = uni.createSelectorQuery().in(getCurrentInstance());
  initPostion(1)
 })

 const initPostion = (index) => {
  query.value.select('.item' + index).boundingClientRect(data => {
   left.value = data.left + ((data.width - 50) / 2)
  }).exec();
 }

 const changeIndex = (index) => {
    if(index === current.value) return
    current.value = index
    initPostion(index + 1)
 }
</script>
<style scoped>
.tabs_wrap{
    position: relative;
    display:flex;
    align-items: center;
    justify-content: space-around;
    font-size32rpx;
    color#333;
    font-weight: bold;
    height88rpx;
}

.active {
   position: absolute;
   left0;
   bottom0;
   width50px;
   height8rpx;
   background-color#2979ff;
   border-radius50px;
   transition: left 0.3s ease;
  }
</style>

注意事项:
1、uni.createSelectorQuery()在组件中使用要使用in(this)
2、Vue3中没有this,所以要用getCurrentInstance()替代this

以上只是实现效果,未进行复用处理,复用只需修改部分代码即可,比较简单就不在此展示了

觉得有用就点个关注吧!


原文始发于微信公众号(分享是个有趣的东西):uniapp如何实现tab切换线条跟随效果

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/158812.html

(0)
小半的头像小半

相关推荐

发表回复

登录后才能评论
极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!