1. 程式人生 > 程式設計 >element-ui 實現響應式導航欄的示例程式碼

element-ui 實現響應式導航欄的示例程式碼

開始之前

按照計劃,前端使用Vue.js+Element UI,但在設計導航欄時,發現element沒有提供傳統意義上的頁面頂部導航欄元件,只有一個可以用在很多需要選擇tab場景的導航選單,便決定在其基礎上改造,由於我認為實現移動端良好的體驗是必須的,所以便萌生了給其增加響應式功能的想法。

需求分析與拆解

假設我們的導航欄有logo和四個el-menu-item。

給window繫結監聽事件,當寬度小於a時,四個連結全部放入右側el-submenu的子選單:

element-ui 實現響應式導航欄的示例程式碼

當寬度大於a時,右側el-submenu不顯示,左側el-menu-item正常顯示:

element-ui 實現響應式導航欄的示例程式碼

所以,先建立一個數組,儲存所有所需的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">
  <i class="el-icon-s-fold" style="font-size:28px;color:#2d2d2d;"></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 實現響應式導航欄的示例程式碼的文章就介紹到這了,更多相關element 響應式導航欄內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!