前端Vue項目——初始化及導航欄

一、項目初始化

  創建webpack模板項目如下所示:

MacBook-Pro:PycharmProjects hqs$ vue init webpack luffy_project

? Project name luffy_project
? Project description A Vue.js project
? Author hqs
? Vue build standalone
? Install vue-router? Yes
? Use ESLint to lint your code? No
? Set up unit tests No
? Setup e2e tests with Nightwatch? No
? Should we run `npm install` for you after the project has been created? (recommended) npm

   vue-cli · Generated "luffy_project".

  根據提示啟動項目:

$ cd luffy_project/
$ npm run dev

  由於在初始化時選擇了vue-router,因此會自動創建/src/router/index.js文件。

  刪除Helloworld組件相關信息后,index.js文件內容如下所示:

import Vue from 'vue'
import Router from 'vue-router'
// @絕對路徑 檢索到 ...src/

// 如果Router當做局部模塊使用一定要Vue.use(Router)
// 以後在組件中,可以通過this.$router 獲取Router實例化對象
// 路由信息對象 this.$routes 獲取路由配置信息
Vue.use(Router)

// 配置路由規則
export default new Router({
  routes: [
    {
'path': '/'
} ] })

二、基於ElementUI框架實現導航欄

1、elementUI——適合Vue的UI框架

  elementUI是一個UI庫,它不依賴於vue,但確是當前和vue配合做項目開發的一個比較好的UI框架。

(1)npm安裝

  推薦使用 npm 的方式安裝,能更好地和 webpack 打包工具配合使用。

$ npm i element-ui -S

(2)CDN

  目前可以通過 unpkg.com/element-ui 獲取到最新版本的資源,在頁面上引入 js 和 css 文件即可開始使用。

<!-- 引入樣式 -->
<link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
<!-- 引入組件庫 -->
<script src="https://unpkg.com/element-ui/lib/index.js"></script>

  使用CND引入 Element 需要在鏈接地址上鎖定版本,以免將來 Element 升級時受到非兼容性更新的影響。鎖定版本的方法請查看 unpkg.com。

2、引入 Element

  在項目中可以引入整個Element,或者是根據需要僅引入部分組件。

(1)完整引入

  在 main.js 中寫入如下內容:

import Vue from 'vue'
import App from './App'
import router from './router'
// elementUI導入
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'  // 注意樣式文件需要單獨引入
// 調用插件
Vue.use(ElementUI);

Vue.config.productionTip = false;

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  components: { App },
  template: '<App/>'
});

  以上代碼便完成了 Element 的完整引入。

  嘗試在App.vue使用elementui的Button按鈕:

<template>
  <div id="app">
    <!-- 導航區域 -->
    <el-button type="info">信息按鈕</el-button>

    <router-view/>
  </div>
</template>

<script>
export default {
  name: 'App'
}
</script>

  显示效果:

   

(2)按需引入

  藉助 babel-plugin-component,可以只引入需要的組件,以達到減小項目體積的目的。

  首先安裝babel-plugin-component:

$ npm install babel-plugin-component -D

  然後將.babelrc文件修改如下:

{
  "presets": [["es2015", { "modules": false }]],
  "plugins": [
    [
      "component",
      {
        "libraryName": "element-ui",
        "styleLibraryName": "theme-chalk"
      }
    ]
  ]
}

  如果只希望引入部分組件,如Buttion何Select,那麼需要在 main.js 中寫如下內容:

import Vue from 'vue';
import { Button, Select } from 'element-ui';
import App from './App.vue';

Vue.component(Button.name, Button);
Vue.component(Select.name, Select);
/* 或寫為
 * Vue.use(Button)
 * Vue.use(Select)
 */

new Vue({
  el: '#app',
  render: h => h(App)
});

3、導航欄實現

  首先創建/src/components/Common/LuffyHeader.vue文件:

<template>
  <!-- element-ui -->
  <el-container>
    <el-header height = '80px' >
      <div class="header">
        <div class="nav-left">
          <img src="https://www.luffycity.com/static/img/head-logo.a7cedf3.svg" alt="">
        </div>
        <div class="nav-center">
          <ul>
            <li>
              <a href="#">
                導航鏈接
              </a>
            </li>
          </ul>
        </div>
        <div class="nav-right">
          <span>登錄</span>
          &nbsp;| &nbsp;
          <span>註冊</span>
        </div>
      </div>
    </el-header>
  </el-container>
</template>

<script>
  export default {
    name: 'LuffyHeader',
    data(){
      return {
      }
    },
  };
</script>

  再創建/static/global/global.css文件:

* {
  padding: 0;
  margin: 0;
}

body {
  font-size: 14px;
  color: #4a4a4a;
  font-family: PingFangSC-Light; /*蘋果設計的一款全新的中文系統字體,該字體支持蘋果的動態字體調節技術*/
}

ul {
  list-style: none;
}

a {
  text-decoration: none;
}

  最後在App.vue中引入和使用組件:

<template>
  <div id="app">
    <!-- 導航區域 -->
    <LuffyHeader/>
    <router-view/>
  </div>
</template>

<script>
  import LuffyHeader from '@/components/Common/LuffyHeader'
  export default {
    name: 'App',
    components:{
      LuffyHeader
    }
  }
</script>

  显示效果如下所示:

  

三、導航欄路由跳轉

1、組件創建和路由配置編寫

  添加“首頁”、“免費課程”、“輕課”、“學位課”四大組件,因此創建如下文件:

src/components/Home/Home.vue
src/components/Course/Course.vue
src/components/LightCourse/LightCourse.vue
src/components/Micro/Micro.vue

  在src/router/index.js中引入組件,配置路由規則:

import Vue from 'vue'
import Router from 'vue-router'
// @絕對路徑 檢索到 ...src/

// 如果Router當做局部模塊使用一定要Vue.use(Router)
// 以後在組件中,可以通過this.$router 獲取Router實例化對象
// 路由信息對象 this.$routes 獲取路由配置信息
import Home from '@/components/Home/Home'
import Course from '@/components/Course/Course'
import LightCourse from '@/components/LightCourse/LightCourse'
import Micro from '@/components/Micro/Micro'

Vue.use(Router)

// 配置路由規則
export default new Router({
  routes: [
    {
      path: '/',
      redirect: '/home'   // 訪問/,直接跳轉到/home路徑
    },
    {
      path: '/home',
      name: 'Home',
      component: Home
    },
    {
      path: '/course',
      name: 'Course',
      component: Course
    },
    {
      path: '/home/light-course',
      name: 'LightCourse',
      component: LightCourse
    },
    {
      path: '/micro',
      name: 'Micro',
      component: Micro
    }
  ]
})

2、導航鏈接編寫

  修改 LuffyHeader.vue頁面,編寫導航鏈接:

<template>
  <!-- element-ui -->
  <el-container>
    <el-header height = '80px' >
      <div class="header">
        <div class="nav-left">
          <img src="https://www.luffycity.com/static/img/head-logo.a7cedf3.svg" alt="">
        </div>
        <div class="nav-center">
          <ul>
            <li v-for="(list, index) in headerList" :key="list.id">
              <a href="#">
                {{ list.title }}
              </a>
            </li>
          </ul>
        </div>
        <div class="nav-right">
          <span>登錄</span>
          &nbsp;| &nbsp;
          <span>註冊</span>
        </div>
      </div>
    </el-header>
  </el-container>
</template>

<script>
  export default {
    name: 'LuffyHeader',
    data() {
      return {
        headerList: [
          {id: '1', name: 'Home', title: '首頁'},
          {id: '2', name: 'Course', title: '免費課程'},
          {id: '3', name: 'LightCourse', title: '輕課'},
          {id: '4', name: 'Micro', title: '學位課程'}
        ],
        isShow: false
      }
    }
  }
</script>

  編寫headerList列表及列表中的導航對象,在 導航欄中遍歷對象獲取對應信息,显示在頁面效果如下所示:

  

3、router-link路由跳轉

  經過上面的編寫,雖然導航欄已經可以正常显示,但是a標籤是不會做自動跳轉的。 需要使用 router-link 進一步改寫LuffyHeader.vue,使得路由跳轉得以渲染對應組件:

<template>
  <!-- element-ui -->
  <el-container>
    <el-header height = '80px' >
      <div class="header">
        <div class="nav-left">
          <img src="https://www.luffycity.com/static/img/head-logo.a7cedf3.svg" alt="">
        </div>
        <div class="nav-center">
          <ul>
            <li v-for="(list, index) in headerList" :key="list.id">
              <router-link :to="{name:list.name}">
                {{ list.title }}
              </router-link>
            </li>
          </ul>
        </div>
        <div class="nav-right">
          <span>登錄</span>
          &nbsp;| &nbsp;
          <span>註冊</span>
        </div>
      </div>
    </el-header>
  </el-container>
</template>

<script>
  export default {
    name: 'LuffyHeader',
    data() {
      return {
        headerList: [
          {id: '1', name: 'Home', title: '首頁'},
          {id: '2', name: 'Course', title: '免費課程'},
          {id: '3', name: 'LightCourse', title: '輕課'},
          {id: '4', name: 'Micro', title: '學位課程'}
        ],
        isShow: false
      }
    }
  }
</script>

  使用to='{name:list.name}’設置命令路由,這樣點擊a標籤就可以跳轉了。显示效果如下所示:

  

  可以看到雖然點擊了輕課,但是和其他導航項樣式沒有任何分別,需要設置路由active樣式完成優化。

4、linkActiveClass設置路由的active樣式

  linkActiveClass 全局配置 <router-link> 的默認“激活 class 類名”。

  active-class 設置 鏈接激活時使用的 CSS 類名。默認值可以通過路由的構造選項 linkActiveClass 來全局配置。

(1)在路由配置linkActiveClass

  在 src/router/index.js 中做如下配置:

import Vue from 'vue'
import Router from 'vue-router'
// @絕對路徑 檢索到 ...src/

// 如果Router當做局部模塊使用一定要Vue.use(Router)
// 以後在組件中,可以通過this.$router 獲取Router實例化對象
// 路由信息對象 this.$routes 獲取路由配置信息
import Home from '@/components/Home/Home'
import Course from '@/components/Course/Course'
import LightCourse from '@/components/LightCourse/LightCourse'
import Micro from '@/components/Micro/Micro'

Vue.use(Router)

// 配置路由規則
export default new Router({
  linkActiveClass: 'is-active',
  routes: [
    {
      path: '/',
      redirect: '/home'   // 訪問/,直接跳轉到/home路徑
    },
    ......
    {
      path: '/micro',
      name: 'Micro',
      component: Micro
    }
  ]
})

(2)在LuffyHeader.vue中配置路由active樣式

<template>
  ......省略
</template>

<script>
  ......省略
</script>

<style lang="css" scoped>
  .nav-center ul li a.is-active{
    color: #4a4a4a;
    border-bottom: 4px solid #ffc210;
  }
</style>

(3)显示效果

  

5、hash模式切換為 history 模式

  vue-router 默認 hash 模式——使用URL的hash來模擬一個完整的URL,於是當URL改變時,頁面不會重新加載。比如http://www.abc.com/#/indexhash值為#/indexhash模式的特點在於hash出現在url中,但是不會被包括在HTTP請求中,對後端沒有影響,不會重新加載頁面。

  如果不想要這種显示比較丑的hash,可以用路由的 history模式,這種模式充分利用 history.pushState API來完成URL跳轉而無需重新加載頁面。

(1)路由修改為history模式

  修改 src/router/index.js 文件如下所示:

import Vue from 'vue'
import Router from 'vue-router'
// @絕對路徑 檢索到 ...src/

// 如果Router當做局部模塊使用一定要Vue.use(Router)
// 以後在組件中,可以通過this.$router 獲取Router實例化對象
// 路由信息對象 this.$routes 獲取路由配置信息
import Home from '@/components/Home/Home'
import Course from '@/components/Course/Course'
import LightCourse from '@/components/LightCourse/LightCourse'
import Micro from '@/components/Micro/Micro'

Vue.use(Router)

// 配置路由規則
export default new Router({
  linkActiveClass: 'is-active',
  mode: 'history',   // 改為history模式
  routes: [
    {
      path: '/',
      redirect: '/home'   // 訪問/,直接跳轉到/home路徑
    },
    .....
  ]
})

  使用history模式時,url就像正常url,例如http://yoursite.com/user/id,這樣比較美觀。

  显示效果如下所示:

  

(2)後端配置

   但是要用好這種模式,需要後台配置支持。vue的應用是單頁客戶端應用,如果後台沒有正確的配置,用戶在瀏覽器訪問http://yoursite.com/user/id 就會返回404,這樣就不好了。

  因此要在服務端增加一個覆蓋所有情況的候選資源:如果 URL 匹配不到任何靜態資源,則應該返回同一個 index.html 頁面,這個頁面就是app依賴的頁面。

  後端配置示例:https://router.vuejs.org/zh/guide/essentials/history-mode.html#%E5%90%8E%E7%AB%AF%E9%85%8D%E7%BD%AE%E4%BE%8B%E5%AD%90

 

【精選推薦文章】

如何讓商品強力曝光呢? 網頁設計公司幫您建置最吸引人的網站,提高曝光率!!

想要讓你的商品在網路上成為最夯、最多人討論的話題?

網頁設計公司推薦更多不同的設計風格,搶佔消費者視覺第一線

不管是台北網頁設計公司台中網頁設計公司,全省皆有專員為您服務

想知道最厲害的台北網頁設計公司推薦台中網頁設計公司推薦專業設計師"嚨底家"!!