前言:學習Vue.js高仿餓了么課程過程中,總結了這個Web App項目從准備到開發完畢自己覺得很重要的知識點。這一篇主要介紹:項目准備、頁面骨架開發、header組件開發。
項目github地址:https://github.com/66Web/ljq_eleme,歡迎Star。
![]() |
![]() |
App | header |
一、項目分析&學習目標 |
當前最火的MVVM框架
- Vue.js —— 輕量、簡潔、高效、數據驅動、組件化
高仿上線外賣App標准來開發
- 核心模塊 —— 商家模塊
開發一個webApp的全流程
- 需求分析
- 腳手架工具
- 數據mock
- 架構設計
- 代碼編寫
- 自測
- 編譯打包
以線上生產環境的代碼質量作標准
- 代碼開發及測試環節:
- UI標注
- 真實數據演示
- 代碼規范
- 架構設計
- 組件抽象
- 模塊拆分
- 代碼風格統一
- JS變量命名規范
- CSS代碼規范
功能技術分析
- vue-resource: 和后端做數據交互
- vue-router: 做前端路由,實現單頁應用
- 第三方JS庫better-scroll: 列表滾動的實現
- 最大程度組件化: 提高代碼的復用
- html5的localstorage:【收藏商家】功能—存儲在瀏覽器端
- 細節:圖標字體的使用
- 移動端1像素邊框
- css sticky footer布局
- flex 彈性布局
學習目標
- 掌握Vue.js在實戰中的運用
- 學會使用Vue.js【完整的】開發移動端App
- 學會組件化、模塊化的開發
學習內容
- Vue.js框架介紹
- Vue-cli 腳手架 —— 搭建基本代碼框架
- vue-router 官方插件 —— 管理路由
- vue-resource 官方插件 —— 和后端作Ajax通信
- Webpack 開源構建工具(把源代碼經過編譯生成瀏覽器可以識別和運行的代碼)
- es6 + eslint eslint —— es6代碼風格檢查工具
- 工程化 組件化 模塊化
- 移動端常用開發技巧:
- flex彈性布局
- css stickyfooter
- 酷炫的交互設計
二、Vue.js介紹 |
近年來前端開發趨勢
- 舊瀏覽器逐漸淘汰,移動端需求增加
- 前端交互越來越多,功能越來越復雜
- 架構從傳統后台MVC 向REST API+ 前端MV* 遷移
(前者傳統MVC:更新數據會刷新頁面 后者前端MV*: 向后端REST API異步請求數據,局部刷新頁面)
MV* —— MVC、MVP、MVVM
MVVM框架
View ViewModel Model
視圖 通訊 數據
- DOM 觀察者 Javascript對象
- 針對具有復雜交互邏輯的前端應用
- 提供基礎的架構抽象
- 通過Ajax數據持久化,保證前端用戶體驗
- MVVM框架技術:vue.js、react.js、Angular.js
對比Anglar React
- Vue.js更輕量,gzip后大小只有 20K+
- Vuejs更易上手,學習曲線平穩
- 吸收兩家之長,借鑒了angular的指令和react的組件化
vue.js 核心思想
- 數據驅動
- 組件化
組件設計原則
- 頁面上每個獨立的可視/可交互區域視為一個組件
- 每個組件對應一個工程目錄,組件所需要的各種資源在這個目錄下【就近維護】
- 頁面不過是組件的容器,組件可以嵌套自由組合形成完整的頁面
三、Vue-cli開啟Vue項目 |
Vue-cli 是Vue的腳手架工具 —— 幫助寫好Vue基礎代碼的工具
- 目錄結構
- 本地調試
- 代碼部署
- 熱加載
- 單元測試
安裝使用
(sudo) npm install -g vue-cli // sudo:mac環境下有關管理權限的命令
vue init webpack my-project
項目文件
- src文件夾:存放項目源碼
- bulld目錄+ config目錄:webpack配置相關
- node_modules文件夾:npm install 安裝的依賴代碼庫
- static—>.gitkeep: 當這個目錄為空時也可以將它提交到git倉庫中
- babelrc : babel的一些配置,es6語法的轉換
- .editorconfig: 編輯器的配置
- .eslintignore: 忽略語法檢查的目錄文件,一般忽略build目錄和node_modules目錄
- .eslintrc.js: eslint的配置文件
- gitignore: 上傳git倉庫要忽略的一些文件的配置
- index.html: 入口html文件,要使用的css和js文件會在編譯過程中自動插入
- package.json:整個項目的配置文件,一般用來描述項目 ↓
→ scripts: 配置一些需要執行的命令
→ dependencies:開發環境中的依賴
→ devdependencies: 編譯過程中的依賴
項目運行
npm run dev
- src開發目錄下:
- main.js —— 項目入口文件
- App.vue —— 主頁面組件
- vue語法糖: export default { } 一個對象——可以定義一個組件
【小知識點】sublime自動格式化 —— Command+option+L 或 Control+alt+L |
- 在父組件中使用子組件,如Hello.vue:
- 引用
import Hello from './compoments/Hello'
- 注冊
export default{ components: { Hello //es6語法 相當於 'Hello': Hello } }
- 使用標簽
<hello><hello>
開發時的Webpack配置與編譯
- build->dev-server.js 或 Webpack.dev.conf.js
- webpack.base.conf.js : 配置各種文件的Loader
→ 配置默認識別的路徑
resolve: {
extensions: ['.js', '.vue', '.json'],
alias: {
'vue$': 'vue/dist/vue.esm.js',
'@': resolve('src'),
}
}
四、准備工作 |
圖標字體制作
- 在線制作網站:https://icomoon.io/app/#/select
- 將自己的SVG圖標導入,輸出自己的圖標字體文件
- Import Icons → Generate Fonts → preferences修改名稱 → Download
- 使用:icon.css和fonts文件夾下所有文件
項目目錄設計
- src->common目錄下:項目公用文件 js、style、fonts
【css的stylus語法】
npm install stylus stylus-loader --save-dev
|
- resource目錄下:項目圖片文件——可以刪掉無用的assets目錄,但需要修改引用到的地方
- components目錄下:布局、業務功能等分模塊管理組件,如header目錄,footer目錄
- static->css目錄下:reset.css 標簽默認樣式
- 在 index.html 中引入:
<link rel="stylesheet" type="text/css" href="static/css/reset.css">
前后端分離
- Vue SPA —— 前端通過 vue-resource Ajax從后端獲取數據
- 前端最重要的任務:mock數據(后台數據模擬) data.json
{ "seller":{} //商家相關字段
"goods":{} //商品相關字段
"rattings":{} //評論相關字段
}
webpack.dev.conf.js中配置
- 使用 express框架 開啟一個node server,用 express.Router 編寫這些接口請求
- 首先:在 const portfinder = require(‘portfinder’) 后添加
const express = require('express')//開啟一個node server const app = express() //定義一個對象,包含express返回的數據 var appData = require('../data.json') //定義一個對象引入data數據 var seller = appData.seller; var goods = appData.goods; var ratings = appData.ratings; app.use('/api', apiRoutes); //調用app對象
- 然后:找到 devserver{}, 在里面添加
before(app) { app.get('/api/seller', (req, res) => { res.json({ errno: 0, //錯誤碼:實際上是業務方根據業務自己定的 data: seller }) //接口返回json數據,上面配置的數據seller就賦值給data請求后調用 }), app.get('/api/goods', (req, res) => { res.json({ errno: 0, data: goods }) }), app.get('/api/ratings', (req, res) => { res.json({ errno: 0, data: ratings }) }) }
- 注意:每次配置完 express 之后都需要重新啟動
查看json數據
- 在Google地址欄中輸入:localhost:8080/api/seller
- 依賴Google的jsonview插件 —— 安裝 使數據格式化
【Google安裝第三方插件】
—— 轉載自【小白白打醬油博客】 |
![]() |
![]() |
五、頁面骨架開發 |
移動端視口
- index.html 中通過meta設置視口可被縮放,初試寬高設置
<meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0, minimum-scale=1.0, user-scalable=no">
App.vue 中把頁面拆為三個區塊
<div id="app">
<div class="header">header</div>
<div class="tab">tab</div>
<div class="content">content</div>
</div>
然后,分別抽成一個組件,引用 —— 所有組件自定義標簽名不可與html本身標簽重合 'v-header': header
移動端經典布局 flex
<div class="tab"> <div class="tab-item">商品</div> <div class="tab-item">評論</div> <div class="tab-item">商家</div> </div>
.tab
display: flex
width: 100%
height: 40px
line-height: 40px
.tab-item
flex:1
text-align: center
vueRouter
- Vue2.0 使用 <router-link> 進行【導航】
<router-link :to="{ path: '/goods' }">商品</router-link>
- 【路由外鏈 】<router-view> —— 單頁面切換的內容頁,替換content div區塊
<router-view></router-view>
-
main.js 中設置單頁面應用路由的【掛載組件】—— 默認App.vue 也可以自定義組件如layout.vue
/* eslint-disable no-new */ new Vue({ el: '#app', router, components: { App }, template: '<App/>' })
-
配置【路由map】:router->index.js
export default new Router({ mode: 'history', routes: [ { path: '/', redirect: '/goods',//默認頁面重定向 }, { path: '/goods', component: goods }, { path: '/ratings', component: ratings }, ] })
- 【點擊】高亮顯示 a.router-link-active
#app .tab .tab-item>a{ display: block; font-size: 14px; color: rgb(77, 85, 93); } #app .tab .tab-item>a.router-link-active{ color: rgb(240, 20, 20) }
1像素border實現
- 錯誤做法:直接給tab加1像素邊框 X
.tab{ border-bottom: 1px solid rgba(7,17,27,0.1) }
- 問題是:這段代碼在PC端顯示,是1像素,但是在手機端顯示,就不是1像素。
- 因為手機端有一個DPR的概念:它的物理像素是設備像素的兩倍。所以iPhone6上面可能就是一個2像素的邊框
【PC開發中用手機實時預覽的小技巧】
|
- 正確做法:給 tab 加一個偽類:after , 讓它是一條1像素的線,然后在DBR為2或3的手機端縮放 √
<div class="tab border-1px">
- 定義mixin.styl: 通過css預處理器的函數方法,實現偽類線
border-1px($color) position: relative &:before display: block position: absolute left:0 top: 0 width: 100% border-bottom: 1px solid $color content: '' &:after display: block position: absolute left:0 bottom: 0 width: 100% border-top: 1px solid $color content: ''
- 定義base.styl: 實現不同DBR的移動端的縮放
@media(-webkit-min-device-pixel-ratio: 1.5),(min-device-pixel-ratio: 1.5)//DPR為1.5的縮放0.7倍 .border-1px &:before -webkit-transform: scaleY(0.7) transform:scaleY(0.7) &:after -webkit-transform: scaleY(0.7) transform:scaleY(0.7)
@media(-webkit-min-device-pixel-ratio: 2),(min-device-pixel-ratio: 2)//DPR為2的縮放0.5倍 .border-1px &:before -webkit-transform: scaleY(0.5) transform:scaleY(0.5) &:after -webkit-transform: scaleY(0.5) transform:scaleY(0.5) - 定義index.styl: 引用所有styl文件,最后在 main.js 中全局引用
@import"./mixin" //import后無空格 @import"./icon" @import"./base"
main.js: import '@/common/stylus/index.styl' //import后有空格
六、header組件開發 |
vue-resource
- 安裝 vue-resource
npm install vue-resource --save
注意:每次install完插件等之后需要重新啟動項目
- main.js 文件中:
import VueResource from 'vue-resource' Vue.use(VueResource)
之后就可以在項目任何地方:使用 this.$http 命令
- App.vue 組件中:
- export module{} 外:
const ERR_OK = 0; //定義常量,增強程序可讀性
- export module{} 內:
data() { return { seller:{} //維護數據 seller } }
- 異步請求數據,返回的是Promise對象
created: function () { this.$http.get('/api/seller') //發送get請求, .then(function(res){ //.then方法 請求完成后調用 //第一個函數是請求成功后方法 }, function (err) { //第二個函數是請求失敗后方法 }) }
使用ES6 箭頭函數:箭頭函數前后必須有空格
created: function () { this.$http.get('/api/seller') .then((res) => { res = res.body //拿到response返回的promise對象的body(Data Object) if (res.errno === ERR_OK) { this.seller = res.data; //console.log(this.seller) } }, (err) => { }) }
外部組件
- 父組件 App.vue 中 <header> 組件標簽中用v-bind綁定seller屬性,傳給子組件seller數據
<v-header :seller="seller"></v-header>
- 子組件 header.vue 中通過 props屬性 獲取父組件傳來的seller數據
props: { seller: { type: Object } }
- 模板對應位置 顯示 對應seller.xxx 子數據
- <img>標簽: 使用seller數據圖片地址,v-bind綁定src屬性
:src="seller.avatar"
- 文本內容: 雙向數據綁定顯示seller數據
{{seller.name}}
- 如果要獲取的是 seller數據對象的 子對象數組的 某一項:因為異步獲取數據,子對象可能為undefined,需要先 v-if 判斷是否存在
<div class="support" v-if="seller.supports"> <span class="icon" :class="this.classMap[seller.supports[0].type]"></span> <span class="text">{{seller.supports[0].description}}</span> </div>
- 定義 classMap數組,通過獲取seller數據中的索引值,應用對應索引的class
created (){ this.classMap = ['decrease','descount','guarantee','invoice','special'] }
<span class="icon" :class="this.classMap[seller.supports[0].type]"></span>
- mixin.styl 文件中偽函數:實現圖片在不同DPR下引用不同的圖片路徑
bg-image($url) background-image: url($url+"@2x.png") @media (-webkit-min-device-pixel-ratio: 3),(min-device-pixel-ratio: 3) background-image: url($url+"@3x.png")
- 公告內容 —— 文字【省略號效果】
white-space: nowrap overflow: hidden text-overflow: ellipsis
- 背景圖片【模糊濾鏡效果】
.background position: absolute top: 0 left: 0 width: 100% height: 100% z-index: -1 filter: blur(10px)
詳情彈層頁
- 實現彈出層
- v-show指令 —— 控制彈出層的顯示/隱藏
<div class="detail" v-show="detailShow"></div>
data () { return { detailShow: false //通過改變數據detailShow 的true/false,控制元素的顯示/隱藏 } }
- @click —— 觸發點擊事件,執行顯示函數
<div class="bulletin-wrapper" @click="showDetail>
methods: { showDetail () { this.detailShow = true; } }
【Css Sticky footers布局】
|
Star組件抽象
- 目標:為了增強擴展性,使足夠靈活
- 思路:
- v-for —— 根據分數 遍歷itemClasses 顯示星星樣式
<div class="star" :class="starType"> <span v-for="itemClass in itemClasses" :key="itemClass.value" :class="itemClass" class="star-item"> </span> </div>
- props —— 從父組件接收兩個參數:size尺寸,score分數
props:{ size: { type: Number }, score: { type: Number } }
- :class —— 綁定動態class, 在不同的調用地方, 可以設置不同的樣式
@import "../../common/stylus/mixin" .star .star-item display: inline-block background-repeat: no-repeat &.star-48 .star-item width: 20px height: 20px margin-right: 22px background-size: 20px 20px &:last-child margin-right: 0 &.on bg-image('star48_on') &.half bg-image('star48_half') &.off bg-image('star48_off') &.star-36 .star-item width: 15px height: 15px margin-right: 16px background-size: 15px 15px &:last-child margin-right: 0 &.on bg-image('star36_on') &.half bg-image('star36_half') &.off bg-image('star36_off') &.star-24 .star-item width: 10px height: 10px margin-right: 3px background-size: 10px 10px &:last-child margin-right: 0 &.on bg-image('star24_on') &.half bg-image('star24_half') &.off bg-image('star24_off')
- computed —— 根據size 計算出動態的class;根據score push對應個數的全亮星星class;判斷如果有半分或不足5分的,push進半星class和灰色星class;根據數組中對應的class顯示對應的星星圖片
const LENGTH = 5; const CLS_ON = 'on'; const CLS_HALF = 'half'; const CLS_OFF = 'off'; computed: { starType() { return 'star-' + this.size; //根據size 計算出動態的class }, itemClasses() { let result = []; let score = Math.floor(this.score*2)/2; let hasDecimal = score % 1 !== 0; let integar = Math.floor(score); for(let i=0; i<integar; i++){ result.push(CLS_ON) //根據score 在itemClasses中push進對應個數的全亮星星class } if(hasDecimal) { result.push(CLS_HALF);//判斷如果有半分或不足5分的,push進半星class和灰色星class } while (result.length < LENGTH) { result.push(CLS_OFF) } return result; //根據itemClasses中對應的class顯示對應的星星圖片 } }
- 樣式: 除了通用樣式,還有根據不同size計算出的全部class的樣式
小標題自適應線
- 避免:寫死百分比,這樣寬屏幕會間隔很大,窄屏幕間隔會幾乎看不到
- flex布局:
<div class="title">
<div class="line"></div>
<div class="text">優惠信息</div>
<div class="line"></div>
</div>
.title
display: flex
width: 80%
margin: 30px auto 24px auto
.line
flex: 1
position: relative
top: -6px
border-bottom: 1px solid rgba(255, 255, 255, 0.2)
.text
padding: 0 12px
font-size: 14px
【Postcss工具】
|
過渡動畫組件 transition
<transition name="fade">
<div class="detail">
</transition>
.detail
opacity: 1
background: rgba(7, 17, 27, 0.8)
&.fade-enter-active, &.fade-leave-active
transition: all 0.5s ease
&.fade-enter, &.fade-leave-active
opacity: 0
background: rgba(7, 17, 27, 0)
iPhone手機背景模糊效果
backdrop-filter: blur(10px) // PC端和其它手機看不出效果
注:項目來自慕課網