這篇文章主要為大家展示了element-ui如何實現響應式導航欄,內容簡而易懂,希望大家可以學習一下,學習完之后肯定會有收獲的,下面讓小編帶大家一起來看看吧。
開始之前
按照計劃,前端使用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
class="right-item"
v-if="Object.keys(rightNavItems).length === 0?false:true"
index="10"
>
<template slot="title">
<i class="el-icon-s-fold" ></i>
</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啦~)
以上就是關于element-ui如何實現響應式導航欄的內容,如果你們有學習到知識或者技能,可以把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。