歡迎您光臨本站 註冊首頁

【vue.js】element-ui 實現響應式導航欄的示例代碼

←手機掃碼閱讀     techdo @ 2020-05-09 , reply:0

開始之前
按照計劃,前端使用Vue.js+Element UI,但在設計導航欄時,發現element沒有提供傳統意義上的頁面頂部導航欄組件,只有一個可以用在很多需要選擇tab場景的導航菜單,便決定在其基礎上改造,由於我認為實現移動端良好的體驗是必須的,所以便萌生了給其增加響應式功能的想法。
需求分析與拆解
假設我們的導航欄有logo和四個el-menu-item。
給window綁定監聽事件,當寬度小於a時,四個鏈接全部放入右側el-submenu的子菜單:
當寬度大於a時,右側el-submenu不顯示,左側el-menu-item正常顯示:
所以,先創建一個數組,存儲所有所需的item:
navItems: [ { name: "Home", indexPath: "/home", index: "1" }, { name: "Subscribe", indexPath: "/subscribe", index: "2"}, { name: "About", indexPath: "/about", index: "3" }, { name: "More", indexPath: "/more", index: "4" } ]
監聽寬度
很明顯功能實現的關鍵是隨時監聽窗口的變化,根據對應的寬度做出響應,在data中,我使用screenWidth變量來存儲窗口大小,保存初始打開頁面時的寬度:
data() { return { screenWidth: document.body.clientWidth ...... } }
接下來在mounted中綁定屏幕監聽事件,將最新的可用屏幕寬度賦給screenWidth:
mounted() { window.onresize = () => { this.screenWidth = document.body.clientWidth } }
(關於document和window中N多的關於高度和寬度的屬性,可以參考這篇文章。)
為了防止頻繁觸發resize函數導致頁面卡頓,可以使用一個定時器,控制下screenWidth更新的頻率:
watch: { screenWidth(newValue) {

 // 為了避免頻繁觸發resize函數導致頁面卡頓,使用定時器 

if (!this.timer) { 

// 一旦監聽到的screenWidth值改變,就將其重新賦給data裡的screenWidth this.screenWidth = newValue; this.timer = true; setTimeout(() => { //console.log(this.screenWidth); this.timer = false; }, 400); } } }
顯示
有了屏幕寬度的實時數據後,就可以以computed的方式控制menuItem了。
computed: { ... leftNavItems: function() { return this.screenWidth >= 600 ? this.navItems : {}; }, rightNavItems: function() { return this.screenWidth < 600 ? this.navItems : {}; } },
通過簡單的判斷即可在窗口寬度變化時,將菜單裡的內容放入預先設置的正常菜單或者當寬度小於600時顯示的右側下拉菜單,附上html部分代碼:

<el-menu text-color="#2d2d2d" id="navid" class="nav" mode="horizontal" select="handleSelect">

    <el-menu-item class="logo" index="0" route="/home">

        <img class="logoimg" src="../assets/img/logo.png" alt="logo"/> 

    </el-menu-item>

    <el-menu-item :key="key" v-for="(item,key) in leftNavItems" :index="item.index" :route="item.activeIndex">

        {{item.name}}

    </el-menu-item>

    <el-submenu style="float:right;" class="right-item" v-if="Object.keys(rightNavItems).length === 0?false:true" index="10">

        <template slot="title">

            <em class="el-icon-s-fold" style="font-size:28px;color:#2d2d2d;"></em> 

        </template>

        <el-menu-item :key="key" v-for="(item,key) in rightNavItems" :index="item.index" :route="item.activeIndex">

            {{item.name}}

        </el-menu-item>

    </el-submenu>

</el-menu>


總結
總的來說,一個丐版就算完成了,這裡只提供了一種可能的思路,如需實踐可以增加更多判斷規則及功能。(主要是已經轉用Vuetify啦~)


[techdo ] 【vue.js】element-ui 實現響應式導航欄的示例代碼已經有564次圍觀

http://coctec.com/docs/vue-js/show-post-233423.html