使用vue寫一個可復(fù)用的導(dǎo)航欄組件

今天在重構(gòu)的時候,發(fā)現(xiàn)項目中有很多的導(dǎo)航欄,但是之前處理導(dǎo)航欄時,直接一行l(wèi)i搞定,超出這個寬度就overflow: hidden;。額。這次重構(gòu)的主要目的也是應(yīng)項目要求,做到響應(yīng)式。我就按element-ui的樣子做了一套適用于我們項目的導(dǎo)航欄組件。
代碼來嘍

<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>

我做的導(dǎo)航欄是當屏幕<1500的時候,左右的按鈕出現(xiàn),點擊左右按鈕來滾動。所以需要監(jiān)聽屏幕大小的變化。(window.resize)
那么我們一步一步的來,先來做window.resize監(jiān)聽。

第一步:在data中定義一個記錄寬度的屬性
data () {
    return {
      screenWidth: document.body.clientWidth,
      ctrlData: {
        tabIndex: 0,
        iconShow: false
      },
      tabInk: ''
    }
  },
第二步:掛載。用到mounted。
  mounted () {
    let that = this
    // 根據(jù)屏幕大小,顯示左右圖標
    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監(jiān)聽屏幕大小
  watch: {
    // 監(jiān)聽屏幕大小
    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)
    }
  },

監(jiān)聽屏幕大小的事解決了,現(xiàn)在要開始做左右按鈕點擊效果了。

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

這是官網(wǎng)的介紹。也就是說用$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的節(jié)點。但$refs相比document.getElementById來說,會減少獲取dom節(jié)點的消耗。
因為只用到了獲取DOM節(jié)點,就不說$refs對子組件的引用了。具體可以去官網(wǎng)查看。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

完整代碼戳這里

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容