咱們將會選擇使用一些 vue 周邊的庫vue-cli
, vue-router
,vue-resource
,vuex
css
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.0html
最終咱們將會構建出一個小 demo,不廢話,直接上圖。vue
1.咱們將會使用 webpack 去爲咱們的模塊打包,預處理,熱加載。若是你對 webpack 不熟悉,它就是能夠幫助咱們把多個 js 文件打包爲1個入口文件,而且能夠達到按需加載。這就意味着,咱們不用擔憂因爲使用太多的組件,致使了過多的 HTTP 請求,這是很是有益於產品體驗的。但咱們並不僅是爲了這個而使用 webpack,咱們須要用 webpack 去編譯 .vue 文件,若是沒有使用一個 loader 去轉換咱們 .vue 文件裏的 style、js 和 html,那麼瀏覽器就沒法識別。node
2.模塊熱加載是 webpack 的一個很是碉堡的特性,將會爲咱們的單頁應用帶來極大的便利。
一般來講,當咱們修改了代碼刷新頁面,那應用裏的全部狀態就都沒有了。這對於開發一個單頁應用來講是很是痛苦的,由於須要從新在跑一遍流程。若是有模塊熱加載,當你修改了代碼,你的代碼會直接修改,頁面並不會刷新,因此狀態也會被保留。webpack
3.Vue 也爲咱們提供了 CSS 預處理,因此咱們能夠選擇在 .vue 文件裏寫 LESS 或者 SASS 去代替原生 CSS。git
4.咱們過去一般須要使用 npm 下載一堆的依賴,可是如今咱們能夠選擇 Vue-cli。這是一個 vue 生態系統中一個偉大創舉。這意味着咱們不須要手動構建咱們的項目,而它就能夠很快地爲咱們生成。github
首先,安裝 vue-cli。(確保你有 node 和 npm)web
npm i -g vue-cli
vue-router
而後建立一個 webpack 項目而且下載依賴vuex
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
查看咱們的應用文件,咱們能夠在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不一樣的地方
1、
vue-router
路由的參數由對象統一變爲了數組要注意。還有則是實例化vue的el
參數已經不能設置html
和body
了,由於在vue2
中是會替換咱們指定的標籤2、咱們必須在實例化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), }] }];
//...
在 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 - 杭州站即將開始,感興趣的小夥伴趕忙報名參會!
👇 點擊「閱讀原文」,便可報名。