vue2.0 構建單頁應用最佳實戰
前言
我們將會選擇使用一些 vue 周邊的庫vue-cli, vue-router,vue-resource,vuex
1.使用 vue-cli 創建項目
2.使用 vue-router 實現單頁路由
3.使用 vuex 管理我們的數據流
4.使用 vue-resource 請求我們的 node 服務端
5.使用 .vue文 件進行組件化的開發
PS:本文 node v6.2.2 npm v3.9.5 vue v2.1.0 vue-router v2.0.3 vuex v2.0.0
最終我們將會構建出一個小 demo,不廢話,直接上圖。

安裝
1.我們將會使用 webpack 去為我們的模塊打包,預處理,熱加載。如果你對 webpack 不熟悉,它就是可以幫助我們把多個 js 文件打包為1個入口文件,並且可以達到按需加載。這就意味着,我們不用擔心由於使用太多的組件,導致了過多的 HTTP 請求,這是非常有益於產品體驗的。但我們並不只是為了這個而使用 webpack,我們需要用 webpack 去編譯 .vue 文件,如果沒有使用一個 loader 去轉換我們 .vue 文件里的 style、js 和 html,那么瀏覽器就無法識別。
2.模塊熱加載是 webpack 的一個非常碉堡的特性,將會為我們的單頁應用帶來極大的便利。
通常來說,當我們修改了代碼刷新頁面,那應用里的所有狀態就都沒有了。這對於開發一個單頁應用來說是非常痛苦的,因為需要重新在跑一遍流程。如果有模塊熱加載,當你修改了代碼,你的代碼會直接修改,頁面並不會刷新,所以狀態也會被保留。
3.Vue 也為我們提供了 CSS 預處理,所以我們可以選擇在 .vue 文件里寫 LESS 或者 SASS 去代替原生 CSS。
4.我們過去通常需要使用 npm 下載一堆的依賴,但是現在我們可以選擇 Vue-cli。這是一個 vue 生態系統中一個偉大創舉。這意味着我們不需要手動構建我們的項目,而它就可以很快地為我們生成。
首先,安裝 vue-cli。(確保你有 node 和 npm)
npm i -g vue-cli
然后創建一個 webpack 項目並且下載依賴
vue init webpack vue-tutorial

cd vue-tutorial
npm i
接着使用 npm run dev 在熱加載中運行我們的應用
這一行命令代表着它會去找到package.json的scripts對象,執行node bulid/dev-server.js。在這文件里,配置了 Webpack,會讓它去編譯項目文件,並且運行服務器,我們在localhost:8080即可查看我們的應用。

這些都准備好后,我們需要為我們的路由、XHR 請求、數據管理下載三個庫,我們可以從 vue 的官網中找到他們。另外我們使用bootstrap作為我的 UI 庫
npm i vue-resource vue-router vuex bootstrap --save
初始化(main.js)
查看我們的應用文件,我們可以在src目錄下找到App.vue和main.js。main.js將會作為我們應用的入口文件而App.vue會作為我們應用的初始化組件。先讓我們來完善下main.js
// src/main.js
import Vue from 'vue'
import VueRouter from 'vue-router'
import VueResource from 'vue-resource'
import App from './App'
import Home from './components/Home'
import 'bootstrap/dist/css/bootstrap.css'
Vue.use(VueRouter) Vue.use(VueResource)
const routes = [{ path : '/', component : Home },{ path : '/home', component : Home }];
const router = new VueRouter({ routes });
/* eslint-disable no-new */
// 實例化我們的Vue
var app = new Vue({ el: '#app', router, ...App, });
這有兩個與1.0不同的地方
一、
vue-router路由的參數由對象統一變為了數組要注意。還有則是實例化vue的el參數已經不能設置html和body了,因為在vue2中是會替換我們指定的標簽二、我們必須在實例化vue的時候指定渲染什么組件,以前我們是通過路由來指定如
router.start(App, '#app'),而在vue2中則不需要了
可以發現我們在main.js里使用了兩個組件App.vue和Home.vue,稍后讓我們具體實現它們的內容。
而我們的index.html只需要保留<div id="app"></div>即可,我們的 Vue 在實例化時設置了el : '#app' 所以會替換這標簽,為我們App組件的內容
//index.html
<div id="app"></div>
我們的初始化就到這結束了,接下來讓我們開始創建組件。
創建首頁組件
首先我們在 App.vue 里為我們的應用寫個頂部導航。
// src/App.vue
<template>
<div id="wrapper"> <nav class="navbar navbar-default"> <div class="container"> <a class="navbar-brand" href="#"> <i class="glyphicon glyphicon-time"></i> 計划板
</a> <ul class="nav navbar-nav"> <li><router-link to="/home">首頁</router-link></li> <li><router-link to="/time-entries">計划列表</router-link></li> </ul> </div> </nav> <div class="container"> <div class="col-sm-3"> </div> <div class="col-sm-9"> <router-view></router-view> </div> </div> </div>
</template>
除了我們的navbar以外,我們還需要一個.container去放我們其余需要展示的信息。並且在這里我們要放一個router-view標簽,vue-router的切換就是通過這個標簽開始顯現的。
在這有個與1.0不同的地方
以前我們可以直接通過寫a標簽 然后寫v-link屬性進行路由跳轉,在 vue2 中改為了寫
<router-link>標簽再寫對應屬性(to)進行跳轉
接着,我們需要創建一個Home.vue作為我們的首頁
// src/components/Home.vue
<template>
<div class="jumbotron"> <h1>任務追蹤</h1> <p> <strong> <router-link to="/time-entries">創建一個任務</router-link> </strong> </p> </div>
</template>
不出意外的話,你可以看見如下效果

創建側邊欄組件
目前我們首頁左側還有一塊空白,我們需要它放下一個側邊欄去統計所有計划的總時間。
// src/App.vue //... <div class="container">
<div class="col-sm-3"> <sidebar></sidebar> </div> <div class="col-sm-9"> <router-view></router-view> </div> </div> //...
<script>
import Sidebar from './components/Sidebar.vue' export default { components: { 'sidebar': Sidebar }, } </script>
在Sidebar.vue我們需要通過 store 去獲取總時間,我們的總時間是共享的數據
// src/components/Sidebar.vue
<template>
<div class="panel panel-default"> <div class="panel-heading"> <h1 class="text-center">已有時長</h1> </div> <div class="panel-body"> <h1 class="text-center">{{ time }} 小時</h1> </div> </div>
</template>
<script> export default { computed: { time() {
return this.$store.state.totalTime } } }
</script>
創建計划列表組件
然后我們需要去創建我們的時間跟蹤列表。
// src/components/TimeEntries.vue
<template>
<div> //`v-if`是vue的一個指令 //`$route.path`是當前路由對象的路徑,會被解析為絕對路徑當 //`$route.path !== '/time-entries/log-time'`為`true`是顯示,`false`,為不顯示。 //to 路由跳轉地址
<router-link v-if="$route.path !== '/time-entries/log-time'" to="/time-entries/log-time" class="btn btn-primary"> 創建
</router-link> <div v-if="$route.path === '/time-entries/log-time'"> <h3>創建</h3> </div> <hr> <router-view></router-view> <div class="time-entries"> <p v-if="!plans.length"><strong>還沒有任何計划</strong></p> <div class="list-group"> <-- v-for循環,注意參數順序為(item,index) in items --> <a class="list-group-item" v-for="(plan,index) in plans"> <div class="row"> <div class="col-sm-2 user-details"> <-- `:src`屬性,這個是vue的屬性綁定簡寫`v-bind`可以縮寫為`:` 比如a標簽的`href`可以寫為`:href` 並且在vue的指令里就一定不要寫插值表達式了(`:src={{xx}}`),vue自己會去解析 --> <img :src="plan.avatar" class="avatar img-circle img-responsive" /> <p class="text-center"> <strong> {{ plan.name }}
</strong> </p> </div> <div class="col-sm-2 text-center time-block"> <h3 class="list-group-item-text total-time"> <i class="glyphicon glyphicon-time"></i> {{ plan.totalTime }}
</h3> <p class="label label-primary text-center"> <i class="glyphicon glyphicon-calendar"></i> {{ plan.date }}
</p> </div> <div class="col-sm-7 comment-section"> <p>{{ plan.comment }}</p> </div> <div class="col-sm-1"> <button class="btn btn-xs btn-danger delete-button" @click="deletePlan(index)"> X
</button> </div> </div> </a> </div> </div> </div>
</template>
關於 template 的解釋,都寫在一起了,再看看我們的script
// src/components/TimeEntries.vue
<script> export default { name : 'TimeEntries', computed : { plans () {
// 從store中取出數據 return this.$store.state.list } }, methods : { deletePlan(idx) {
// 稍后再來說這里的方法 // 減去總時間 this.$store.dispatch('decTotalTime',this.plans[idx].totalTime)
// 刪除該計划 this.$store.dispatch('deletePlan',idx) } } } </script>
別忘了為我們的組件寫上一些需要的樣式
// src/components/TimeEntries.vue
<style> .avatar { height: 75px; margin: 0 auto; margin-top: 10px; margin-bottom: 10px; } .user-details { background-color: #f5f5f5; border-right: 1px solid #ddd; margin: -10px 0; } .time-block { padding: 10px; } .comment-section { padding: 20px; } </style>
既然我們的數據是共享的,所以我們需要把數據存在store里
我們在 src 下創建個目錄為store
在store下分別創建4個js文件actions.js,index.js,mutation-types.js,mutations.js
看名字也就知道這4個分別是做啥用的了,建議大家多閱讀閱讀vuex的文檔,多姿勢多動手實踐,慢慢的也就能理解了。
// src/store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex);
// 先寫個假數據
const state = { totalTime: 0, list: [{ name : '二哲', avatar : 'https://sfault-avatar.b0.upaiyun.com/147/223/147223148-573297d0913c5_huge256', date : '2016-12-25', totalTime : '6', comment : '12月25日完善,陪女朋友一起過聖誕節需要6個小時' }] }; export default new Vuex.Store({ state, })
由於新增了頁面和 store 在我們的入口 js 文件里配置下
// src/main.js
import store from './store'
import TimeEntries from './components/TimeEntries.vue'
//...
const routes = [{ path : '/', component : Home },{ path : '/home', component : Home },{ path : '/time-entries', component : TimeEntries, }];var app = new Vue({ el: '#app', router, store, ...App, });
不出意外的話,你可以在/time-entries 路由下看見這樣的頁面

通過vue-Devtools我們可以發現我們的store已經構造好了並且成功從 store 獲取了數據
創建任務組件
這個比較簡單我們直接給出代碼
// src/components/LogTime.vue
<template>
<div class="form-horizontal"> <div class="form-group"> <div class="col-sm-6"> <label>日期</label> <input type="date" class="form-control" v-model="date" placeholder="Date" /> </div> <div class="col-sm-6"> <label>時間</label> <input type="number" class="form-control" v-model="totalTime" placeholder="Hours" /> </div> </div> <div class="form-group"> <div class="col-sm-12"> <label>備注</label> <input type="text" class="form-control" v-model="comment" placeholder="Comment" /> </div> </div> <button class="btn btn-primary" @click="save()">保存</button> <router-link to="/time-entries" class="btn btn-danger">取消</router-link> <hr> </div>
</template>
<script> export default { name : 'LogTime', data() { return { date : '', totalTime : '', comment : '' } }, methods:{ save() {
const plan = { name : '二哲', image : 'https://sfault-avatar.b0.upaiyun.com/888/223/888223038-5646dbc28d530_huge256', date : this.date, totalTime : this.totalTime, comment : this.comment };
this.$store.dispatch('savePlan', plan)
this.$store.dispatch('addTotalTime', this.totalTime)
this.$router.go(-1) } } }
</script>
這個組件很簡單就3個 input 輸入而已,然后就兩個按鈕,保存我們就把數據 push 進我們 store 的列表里
LogTime屬於我們TimeEntries組件的一個子路由,所以我們依舊需要配置下我們的路由,並且利用webpack讓它懶加載,減少我們首屏加載的流量
// src/main.js
//...
const routes = [{ path : '/', component : Home },{ path : '/home', component : Home },{ path : '/time-entries', component : TimeEntries, children : [{ path : 'log-time',
// 懶加載 component : resolve => require(['./components/LogTime.vue'],resolve), }] }];
//...
vuex 部分
在 vue2.0 中廢除了使用事件的方式進行通信,所以在小項目中我們可以使用Event Bus,其余最好都使用 vuex,本文我們使用 Vuex 來實現數據通信
相信你剛剛已經看見了我寫了很多this.$store.dispatch('savePlan', plan) 類似這樣的代碼,我們再次統一說明。
仔細思考一下,我們需要兩個全局數據,一個為所有計划的總時間,一個是計划列表的數組。
src/store/index.js 沒啥太多可介紹的,其實就是傳入我們的state,mutations,actions來初始化我們的 Store。如果有需要的話我們還可能需要創建我們的getter在本例中就不用了。
接着我們看mutation-types.js,既然想很明確了解數據,那就應該有什么樣的操作看起,當然這也看個人口味哈
// src/store/mutation-types.js
// 增加總時間或者減少總時間
export const ADD_TOTAL_TIME = 'ADD_TOTAL_TIME'; export const DEC_TOTAL_TIME = 'DEC_TOTAL_TIME';
// 新增和刪除一條計划
export const SAVE_PLAN = 'SAVE_PLAN'; export const DELETE_PLAN = 'DELETE_PLAN';
// src/store/mutations.js
import * as types from './mutation-types'
export default {
// 增加總時間 [types.ADD_TOTAL_TIME] (state, time) { state.totalTime = state.totalTime + time },
// 減少總時間 [types.DEC_TOTAL_TIME] (state, time) { state.totalTime = state.totalTime - time },
// 新增計划 [types.SAVE_PLAN] (state, plan) {
// 設置默認值,未來我們可以做登入直接讀取昵稱和頭像 const avatar = 'https://sfault-avatar.b0.upaiyun.com/147/223/147223148-573297d0913c5_huge256'; state.list.push(
Object.assign({ name: '二哲', avatar: avatar }, plan) ) },
// 刪除某計划 [types.DELETE_PLAN] (state, idx) { state.list.splice(idx, 1); } };
最后對應看我們的actions就很明白了
// src/store/actions.js
import * as types from './mutation-types'
export default { addTotalTime({ commit }, time) { commit(types.ADD_TOTAL_TIME, time) }, decTotalTime({ commit }, time) { commit(types.DEC_TOTAL_TIME, time) }, savePlan({ commit }, plan) { commit(types.SAVE_PLAN, plan); }, deletePlan({ commit }, plan) { commit(types.DELETE_PLAN, plan) } };
我們的actions其實就是去觸發事件和傳入參數啦
加了這三個文件后我們的 store 終於完整了,更新下我們的代碼
// src/store/index.js 完整代碼
import Vue from 'vue'
import Vuex from 'vuex'
import mutations from './mutations'
import actions from './actions'
Vue.use(Vuex);
const state = { totalTime: 0, list: [] }; export default new Vuex.Store({ state, mutations, actions })
this.$store.dispatch('savePlan', plan)當執行了這樣的方法就會調用actions.js里的savePlan方法,而savePlan又會觸發 mutations里的 types.SAVE_PLAN 最后修改數據視圖更新
PS:在這有個技巧就是,在
mutations里都是用大寫下划線連接,而我們的actions里都用小寫駝峰對應。
個人理解這其實就是一個發布訂閱的模式
mutation-types 記錄我們所有的事件名
mutations 注冊我們各種數據變化的方法
actions 則可以編寫異步的邏輯或者是一些邏輯,再去commit
我們的事件
如果有getter 我們可以把一些需要處理返回的數據放在這即可,不進行業務操作
最后別忘了在我們的main.js里使用我們的store
// src/store/main.js
import store from './store'
// ...
var app = new Vue({ el: '#app', router, store, ...App, });
開始體驗下你自己的任務計划板吧!
最后
通過本文,我們可以學習到許多關於 vue 的特性。
1.了解了 vue-cli 腳手架
2.初步對 webpack 有了一些了解和認識
3.如何用 .vue 愉快的開發
4.使用 vuex 進行組件通信
5.路由(子路由)的應用
6.使用 vue-devtools 觀察我們的數據
個人網站 :http://www.meckodo.com
github地址:https://github.com/MeCKodo/vue-tutorial
-EOF-
【活動推薦】SegmentFault 開發者大會 2016 - 杭州站即將開始,感興趣的小伙伴趕緊報名參會!
👇 點擊「閱讀原文」,即可報名。

