原生JS封装vue Tab切换效果

原生JS封装vue Tab切换效果

本文实例为大家分享了原生JS封装vue Tab切换的具体代码,供大家参考,具体内容如下

先看效果图

原生JS封装vue Tab切换效果

使用的技术

vue,js,css3

vue组件 可以直接使用

<template>
  <div class="bookcircle-header">
    <ul class="wrapper" :class="headerActive == 0 ? 'friend' : 'booklist'">
      <li @click="headerChange(0)" :class="headerActive == 0 ? 'active' : ''">
        书友
      </li>
      <li @click="headerChange(1)" :class="headerActive == 1 ? 'active' : ''">
        书单
      </li>
    </ul>
  </div>
</template>

<script>
export default {
  components: {},
  data() {
    return {
      headerActive: 0,
    };
  },
  computed: {},
  created() {},
  mounted() {
    //初始化抛发
    this.$emit("change", this.headerActive);
  },
  methods: {
    headerChange(index) {
      this.headerActive = index;
      this.$emit("change", index);
    },
  },
};
</script>

<style lang="less" scoped>
.bookcircle-header {
  height: 42px;
  display: flex;
  justify-content: center;
  align-items: center;
  .wrapper {
    width: 286px;
    font-size: 14px;
    height: 29px;
    color: #1489fe;
    border: 1px solid #1489fe;
    border-radius: 14px;
    display: flex;
    justify-content: center;
    align-items: center;
    position: relative;
    box-sizing: border-box; // 解决边框溢出,将border包含在盒子内部
    li {
      flex: 1;
      height: 100%;
      display: flex;
      justify-content: center;
      align-items: center;
      z-index: 2;
    }
    .active {
      color: white;
    }
    &::before {
      content: "";
      width: 143px;
      height: 100%;
      background-color: #1489fe;
      position: absolute;
      top: 0px;
      left: 0px;
      border-radius: 13px 0px 0px 13px;
      z-index: 1;
      transition: all 0.3s;
    }
    &.firend::before {
      transform: translateX(0);
      border-radius: 13px 0px 0px 13px;
    }
    &.booklist::before {
      transform: translateX(100%);
      border-radius: 0px 13px 13px 0px;
    }
  }
}
</style>

实现原理:

使用ul,li以及弹性盒子,首先给父元素设置宽高,然后通过弹性盒子将子元素 li 水平方向展开, 给子元素 li 设置 flex:1,让子元素平分父元素的宽。

然后给父元素设置伪元素,以绝对定位的方式覆盖第一个 li 元素, 通过z-index属性,控制伪元素和子元素的层级显示关系。

然后给伪元素设置 transition 属性 搭配 transform: translateX(); 属性,让元素水平移动就可以了

注意点:

1、虽然切换的点击事件在子元素上,并且也给子元素添加 了active样式,但tab的切换效果并不是通过子元素来实现的,而是通过父元素的伪元素来实现切换效果。
2、必须要根据子元素的 index 给父元素设置动态class, 这样父元素的伪元素才能根据选中的子元素执行切换动画
3、本组件使用的是 淘宝amfe-flexible、 postcss适配,使用时注意适配问题

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