美文网首页
使用vue写一个可复用的导航栏组件

使用vue写一个可复用的导航栏组件

作者: 怪兽别跑biubiubi | 来源:发表于2019-07-20 15:40 被阅读0次

今天在重构的时候,发现项目中有很多的导航栏,但是之前处理导航栏时,直接一行li搞定,超出这个宽度就overflow: hidden;。额。这次重构的主要目的也是应项目要求,做到响应式。我就按element-ui的样子做了一套适用于我们项目的导航栏组件。
代码来喽

<template>
  <div id="data_assets">
    <div class="data_list-tab">
      <div class="el-tabs__header is-top">
        <div class="tabs-nav-wrap is-top is-scrollable">
          // 左按钮 0
          <span class="tabs-nav-prev is-disabled" @click="leftRightBtn(0)" v-if="ctrlData.iconShow === true">
            <i class="el-icon-arrow-left"></i>
          </span>
          // 右按钮 1
          <span class="tabs-nav-next" @click="leftRightBtn(1)" v-if="ctrlData.iconShow === true">
            <i class="el-icon-arrow-right"></i>
          </span>
          <div class="tabs-nav-scroll" id="divx-scroll">
            //使用ref
            <div role="tablist" class="tabs-nav" ref="barList" id="nav-left-right" style="transform: translateX(0px);">
              <div class="tabs-active-bar is-top" :style="tabInk"></div>
              <div @click="changeTab(index)" :class="ctrlData.tabIndex === index ? 'tab-active' : ''"
                v-for="(item, index) in titleName" :key="index" ref="tabItem" class="tabs-item is-top">{{item}}</div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

我做的导航栏是当屏幕<1500的时候,左右的按钮出现,点击左右按钮来滚动。所以需要监听屏幕大小的变化。(window.resize)
那么我们一步一步的来,先来做window.resize监听。

第一步:在data中定义一个记录宽度的属性
data () {
    return {
      screenWidth: document.body.clientWidth,
      ctrlData: {
        tabIndex: 0,
        iconShow: false
      },
      tabInk: ''
    }
  },
第二步:挂载。用到mounted。
  mounted () {
    let that = this
    // 根据屏幕大小,显示左右图标
    window.onresize = () => {
      return (() => {
        window.screenWidth = document.body.clientWidth
        that.screenWidth = window.screenWidth
      })()
    }
    // 每个tabs-item的宽度是140 * tab按钮的长度。
    let lengths = that.titleName.length * 140
    if (document.body.clientWidth < lengths ) {
      that.ctrlData.iconShow = true
    } else {
      that.ctrlData.iconShow = false
    }
  },
第三步:通过watch监听屏幕大小
  watch: {
    // 监听屏幕大小
    screenWidth (val) {
      let that = this
      setTimeout(function () {
        this.screenWidth = val
        let lengths = that.titleName.length * 140 + 300
        if (Number(val) < lengths) {
          that.ctrlData.iconShow = true
        } else {
          that.ctrlData.iconShow = false
          // !!!一定要加的两句话
          // 获取最外层div
          var oUl = that.$refs.barList
          that.move(oUl, 'left', 0);
        }
        return val
      }, 400)
    }
  },

监听屏幕大小的事解决了,现在要开始做左右按钮点击效果了。

methods: {
    changeTab (index) {
      let that = this
      this.ctrlData.tabIndex = index
      // 向父组件传递index
      that.$emit('changeTab', index)
      // 线的位置
      this.tabInk = `transform: translate3d(${140 * index}px, 0, 0)`
    },
    // 向左滑动   // 向右滑动
    leftRightBtn (i) {
      let that = this
      // 获取最外层div
      var oUl = that.$refs.barList
      // 获取div
      var aLi = that.$refs.tabItem
        oUl.style.width = aLi.length * (aLi[0].offsetWidth) + 'px';
      var now = -5 * (aLi[0].offsetWidth);
      if (i === 0) {
        var now1 = -Math.floor((aLi.length / 5)) * 5 * (aLi[0].offsetWidth);
        if (oUl.offsetLeft === -660) {
          that.move(oUl, 'left', 0);
        } else if (oUl.offsetLeft >= 0) {
          that.move(oUl, 'left', 0);
        } else {
          that.move(oUl, 'left', oUl.offsetLeft - now);
        }
      } else if (i === 1) {
        var n = Math.floor((aLi.length * (aLi[0].offsetWidth) + oUl.offsetLeft) / aLi[0].offsetWidth);
        if (n <= 5) {
          that.move(oUl, 'left', 0);
        } else {
          that.move(oUl, 'left', oUl.offsetLeft + now);
        }
      }
    },
    // tabs-item的位置
    move (obj, attr, iTarget) {
      let that = this
      clearInterval(obj.timer)
      obj.timer = setInterval(function () {
        var cur = 0;
        if (attr == 'opacity') {
          cur = Math.round(parseFloat(that.getStyle(obj, attr)) * 100);
        } else {
          cur = parseInt(that.getStyle(obj, attr));
        }
        var speed = (iTarget - cur) / 6;
        speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed);
        if (iTarget === cur) {
          clearInterval(obj.timer);
        } else {
          obj.style[attr] = cur + speed + 'px';
        }
      }, 30);
    },
    getStyle (obj, name) {
      // currentStyle  获取外部的样式  只兼容IE,不兼容火狐和谷歌
      if (obj.currentStyle) {
        return obj.currentStyle[name];
      } else {
        // getComputedStyle  获取外部的样式  兼容火狐谷歌,不兼容IE
        return getComputedStyle(obj, false)[name];
      }
    }
  }

上面在获取DOM元素时用到了$refs,这里说一些$refs的用法。

vue.png
这是官网的介绍。也就是说用$refs需要先写ref。如下:
<input type='text' ref="input1" id='inputs />

// 用法
// 一:<input type='text' ref="input1" id='inputs />
var input1 = that.$refs.input1

// 二:<input type='text' ref="input1" id='inputs />
var input2 = document.getElementById('inputs')

ref被用来给元素或者子组件注册引用信息,引用信息将会注册在父组件的$refs对象上。如果在普通的DOM元素上使用,引用指向的就是DOM元素;如果用在子组件上,引用就指向组件实例:
在我上面的例子中,input的引用信息是input1,$refs是所有注册过的ref的集合。
我用了两种方法都是获取DOM的节点。但$refs相比document.getElementById来说,会减少获取dom节点的消耗。
因为只用到了获取DOM节点,就不说$refs对子组件的引用了。具体可以去官网查看。Vue.js

然后就是样式,样式也很重要。做了一些简单的动画效果、

<style lang="less" scoped>
#data_assets {
  width: 100%;
  min-height: 100%;
  margin: 0 auto;
  background: #f5f7f8;
  .data_list-tab {
    .el-tabs__header {
      padding: 0;
      position: relative;
      margin: 0 0 15px;
      .tabs-nav-wrap {
        box-sizing: border-box;
        overflow: hidden;
        margin-bottom: -1px;
        position: relative;
        padding: 0 20px;
        background: #fff;
        .tabs-nav-scroll {
          overflow: hidden;
          .tabs-nav {
            white-space: nowrap;
            position: relative;
            transition: transform .3s;
            float: left;
            z-index: 2;
            .tabs-active-bar {
              width: 140px;
              position: absolute;
              bottom: 0;
              left: 0;
              height: 2px;
              background-color: #eb6100;
              z-index: 1;
              transition: transform .3s cubic-bezier(.645,.045,.355,1);
              list-style: none;
            }
            .tabs-item {
              text-align: center;
              height: 60px;
              width: 140px;
              box-sizing: border-box;
              line-height: 60px;
              display: inline-block;
              list-style: none;
              font-size: 16px;
              font-weight: 500;
              color: #303133;
              position: relative;
              cursor: pointer;
            }
            .tab-active {
              color: #eb6100;
            }
            .tabs-item:hover {
              color: #eb6100;
            }
          }
        }
        .tabs-nav-prev {
          left: 0;
        }
        .tabs-nav-next, .tabs-nav-prev {
          position: absolute;
          cursor: pointer;
          line-height: 44px;
          font-size: 22px;
          color: #909399;
          top: 8px;
        }
        .tabs-nav-next {
          right: 0;
        }
      }
      .tabs-nav-wrap::after {
        content: "";
        position: absolute;
        left: 0;
        bottom: 0;
        width: 100%;
        height: 2px;
        background-color: #E4E7ED;
        z-index: 1;
      }
    }
  }
}
</style>

在父组件引用:

<Bar :titleName='tabList' @changeTab='changeTab' />
data () {
  return {
    tabList: ['我是按钮1', '我是按钮2', '我是按钮3', '我是按钮4',
              '我是按钮5', '我是按钮6', '我是按钮7', '我是按钮8', '我是按钮9']
  }
},
methods: {
  // 获取子组件传递来的信息
  changeTab (index) {
      this.ctrlData.tabIndex = index
    }
}

效果:


1.png
2.png

完整代码戳这里

相关文章

  • 使用vue写一个可复用的导航栏组件

    今天在重构的时候,发现项目中有很多的导航栏,但是之前处理导航栏时,直接一行li搞定,超出这个宽度就overflow...

  • Vue.js破冰系列-5组件基础(一)

    组件(Component)是可复用的Vue实例,这句话给了我们两个信息,可复用和Vue实例。可复用就是能够重复使用...

  • vue项目的data数据为何一定要return一下?

    用组件化来写vue项目,每个.vue都是一个个组件。 组件是一个可复用的vue的实例。 如果不使用return包裹...

  • Vue 学习笔记入门篇 可复用性的组件

    Vue 学习笔记入门篇 可复用性的组件 7.1 使用组件的原因 作用:提高代码的复用性 7.2 组件的使用方法 全...

  • vue——组件

    组件是什么? 组件是可复用的 Vue 实例,且带有一个名字。 组件的注册与使用 组件与vue实例一样,需要注册,才...

  • 说说 Vue.js 组件

    使用 Vue.js 组件,可以提高控件及其 JS 能力的可复用性。 1 定义第一个组件 Vue.js 组件需要注册...

  • Vue中最重要的角色组件详解

    可复用性的组件详解 使用组件的原因 作用:提高代码的复用性 组件的使用方法 全局注册 优点:所有的Vue实例都可以...

  • 三篇文章学完Vue(二)

    组件 组件是可复用的vue实例,且带有名字。 1.因为组件为可复用的Vue实例,所以它们与new Vue接收相同的...

  • Vue 基础 - 组件

    组件 使用组件可提高代码的复用性 命名规则 vue组件中camelCased(驼峰式)命名与kebab­case(...

  • Vue单文件组件之一:底部导航栏

    移动端场景下经常会要求屏幕底部有Tab类型的导航栏,我们可以把它做成组件,方便复用。 这里采用Vue的单文件组件模...

网友评论

      本文标题:使用vue写一个可复用的导航栏组件

      本文链接:https://www.haomeiwen.com/subject/glpylctx.html