前言
我們將會(huì)選擇使用一些vue周邊的庫(kù) vue-cli , vue-router , vue-resource , vuex
1.使用vue-cli創(chuàng)建項(xiàng)目
2.使用vue-router實(shí)現(xiàn)單頁(yè)路由
3.用vuex管理我們的數(shù)據(jù)流
4.使用vue-resource請(qǐng)求我們的node服務(wù)端
5.使用.vue文件進(jìn)行組件化的開(kāi)發(fā)
PS:本文node v6.2.2 npm v3.9.5 vue v2.1.0 vue-router v2.0.3 vuex v2.0.0
最終我們將會(huì)構(gòu)建出一個(gè)小demo,不廢話,直接上圖。

安裝
1.我們將會(huì)使用webpack去為我們的模塊打包,預(yù)處理,熱加載。如果你對(duì)webpack不熟悉,它就是可以幫助我們把多個(gè)js文件打包為1個(gè)入口文件,并且可以達(dá)到按需加載。這就意味著,我們不用擔(dān)心由于使用太多的組件,導(dǎo)致了過(guò)多的HTTP請(qǐng)求,這是非常有益于產(chǎn)品體驗(yàn)的。但我們并不只是為了這個(gè)而使用webpack,我們需要用webpack去編譯.vue文件,如果沒(méi)有使用一個(gè)loader去轉(zhuǎn)換我們.vue文件里的style、js和html,那么瀏覽器就無(wú)法識(shí)別。
2.模塊熱加載是webpack的一個(gè)非常碉堡的特性,將會(huì)為我們的單頁(yè)應(yīng)用帶來(lái)極大的便利。
通常來(lái)說(shuō),當(dāng)我們修改了代碼刷新頁(yè)面,那應(yīng)用里的所有狀態(tài)就都沒(méi)有了。這對(duì)于開(kāi)發(fā)一個(gè)單頁(yè)應(yīng)用來(lái)說(shuō)是非常痛苦的,因?yàn)樾枰匦略谂芤槐榱鞒獭H绻心K熱加載,當(dāng)你修改了代碼,你的代碼會(huì)直接修改,頁(yè)面并不會(huì)刷新,所以狀態(tài)也會(huì)被保留。
3.Vue也為我們提供了CSS預(yù)處理,所以我們可以選擇在.vue文件里寫(xiě)LESS或者SASS去代替原生CSS。
4.我們過(guò)去通常需要使用npm下載一堆的依賴(lài),但是現(xiàn)在我們可以選擇Vue-cli。這是一個(gè)vue生態(tài)系統(tǒng)中一個(gè)偉大創(chuàng)舉。這意味著我們不需要手動(dòng)構(gòu)建我們的項(xiàng)目,而它就可以很快地為我們生成。
首先,安裝vue-cli。(確保你有node和npm)
npm i -g vue-cli
然后創(chuàng)建一個(gè)webpack項(xiàng)目并且下載依賴(lài)
vue init webpack vue-tutorial

cd vue-tutorial
npm i
接著使用 npm run dev 在熱加載中運(yùn)行我們的應(yīng)用
這一行命令代表著它會(huì)去找到 package.json 的 scripts 對(duì)象,執(zhí)行 node bulid/dev-server.js 。在這文件里,配置了Webpack,會(huì)讓它去編譯項(xiàng)目文件,并且運(yùn)行服務(wù)器,我們?cè)?localhost:8080 即可查看我們的應(yīng)用。

這些都準(zhǔn)備好后,我們需要為我們的路由、XHR請(qǐng)求、數(shù)據(jù)管理下載三個(gè)庫(kù),我們可以從vue的官網(wǎng)中找到他們。另外我們使用 bootstrap 作為我的UI庫(kù)
npm i vue-resource vue-router vuex bootstrap --save
初始化(main.js)
查看我們的應(yīng)用文件,我們可以在src目錄下找到 App.vue 和 main.js 。 main.js將會(huì)作為我們應(yīng)用的入口文件而 App.vue 會(huì)作為我們應(yīng)用的初始化組件。先讓我們來(lái)完善下 main.js
// src/main.jsimport 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 */// 實(shí)例化我們的Vuevar app = new Vue({ el: '#app', router, ...App,});這有兩個(gè)與1.0不同的地方
一、 vue-router 路由的參數(shù)由對(duì)象統(tǒng)一變?yōu)榱藬?shù)組要注意。還有則是實(shí)例化vue的el 參數(shù)已經(jīng)不能設(shè)置 html 和 body 了,因?yàn)樵?vue2 中是會(huì)替換我們指定的標(biāo)簽
二、我們必須在實(shí)例化vue的時(shí)候指定渲染什么組件,以前我們是通過(guò)路由來(lái)指定如router.start(App, '#app') ,而在vue2中則不需要了
可以發(fā)現(xiàn)我們?cè)?main.js 里使用了兩個(gè)組件 App.vue 和 Home.vue ,稍后讓我們具體實(shí)現(xiàn)它們的內(nèi)容。
而我們的 index.html 只需要保留 <div id="app"></div> 即可,我們的Vue在實(shí)例化時(shí)設(shè)置了 el : '#app' 所以會(huì)替換這標(biāo)簽,為我們 App 組件的內(nèi)容
//index.html<div id="app"></div>
我們的初始化就到這結(jié)束了,接下來(lái)讓我們開(kāi)始創(chuàng)建組件。
創(chuàng)建首頁(yè)組件
首先我們?cè)贏pp.vue里為我們的應(yīng)用寫(xiě)個(gè)頂部導(dǎo)航。
// src/App.vue<template> <div id="wrapper"> <nav class="navbar navbar-default"> <div class="container"> <a class="navbar-brand" href="#" rel="external nofollow" > <i class="glyphicon glyphicon-time"></i> 計(jì)劃板 </a> <ul class="nav navbar-nav"> <li><router-link to="/home">首頁(yè)</router-link></li> <li><router-link to="/time-entries">計(jì)劃列表</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 以外,我們還需要一個(gè) .container 去放我們其余需要展示的信息。
并且在這里我們要放一個(gè) router-view 標(biāo)簽, vue-router 的切換就是通過(guò)這個(gè)標(biāo)簽開(kāi)始顯現(xiàn)的。
在這有個(gè)與1.0不同的地方
以前我們可以直接通過(guò)寫(xiě)a標(biāo)簽 然后寫(xiě)v-link屬性進(jìn)行路由跳轉(zhuǎn),在vue2中改為了寫(xiě)<router-link> 標(biāo)簽再寫(xiě)對(duì)應(yīng)屬性(to)進(jìn)行跳轉(zhuǎn)
接著,我們需要?jiǎng)?chuàng)建一個(gè) Home.vue 作為我們的首頁(yè)
// src/components/Home.vue<template> <div class="jumbotron"> <h1>任務(wù)追蹤</h1> <p> <strong> <router-link to="/time-entries">創(chuàng)建一個(gè)任務(wù)</router-link> </strong> </p> </div></template>
不出意外的話,你可以看見(jiàn)如下效果

創(chuàng)建側(cè)邊欄組件
目前我們首頁(yè)左側(cè)還有一塊空白,我們需要它放下一個(gè)側(cè)邊欄去統(tǒng)計(jì)所有計(jì)劃的總時(shí)間。
// 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 我們需要通過(guò)store去獲取總時(shí)間,我們的總時(shí)間是共享的數(shù)據(jù)
// src/components/Sidebar.vue<template> <div class="panel panel-default"> <div class="panel-heading"> <h1 class="text-center">已有時(shí)長(zhǎng)</h1> </div> <div class="panel-body"> <h1 class="text-center">{{ time }} 小時(shí)</h1> </div> </div></template><script> export default { computed: { time() { return this.$store.state.totalTime } } }</script>創(chuàng)建計(jì)劃列表組件
然后我們需要去創(chuàng)建我們的時(shí)間跟蹤列表。
// src/components/TimeEntries.vue<template> <div> //`v-if`是vue的一個(gè)指令 //`$route.path`是當(dāng)前路由對(duì)象的路徑,會(huì)被解析為絕對(duì)路徑當(dāng) //`$route.path !== '/time-entries/log-time'`為`true`是顯示,`false`,為不顯示。 //to 路由跳轉(zhuǎn)地址 <router-link v-if="$route.path !== '/time-entries/log-time'" to="/time-entries/log-time" class="btn btn-primary"> 創(chuàng)建 </router-link> <div v-if="$route.path === '/time-entries/log-time'"> <h3>創(chuàng)建</h3> </div> <hr> <router-view></router-view> <div class="time-entries"> <p v-if="!plans.length"><strong>還沒(méi)有任何計(jì)劃</strong></p> <div class="list-group"> <-- v-for循環(huán),注意參數(shù)順序?yàn)?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`屬性,這個(gè)是vue的屬性綁定簡(jiǎn)寫(xiě)`v-bind`可以縮寫(xiě)為`:` 比如a標(biāo)簽的`href`可以寫(xiě)為`:href` 并且在vue的指令里就一定不要寫(xiě)插值表達(dá)式了(`:src={{xx}}`),vue自己會(huì)去解析 --> <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>關(guān)于template的解釋?zhuān)紝?xiě)在一起了,再看看我們的 script
// src/components/TimeEntries.vue<script> export default { name : 'TimeEntries', computed : { plans () { // 從store中取出數(shù)據(jù) return this.$store.state.list } }, methods : { deletePlan(idx) { // 稍后再來(lái)說(shuō)這里的方法 // 減去總時(shí)間 this.$store.dispatch('decTotalTime',this.plans[idx].totalTime) // 刪除該計(jì)劃 this.$store.dispatch('deletePlan',idx) } } }</script>別忘了為我們的組件寫(xiě)上一些需要的樣式
// 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>既然我們的數(shù)據(jù)是共享的,所以我們需要把數(shù)據(jù)存在 store 里
我們?cè)趕rc下創(chuàng)建個(gè)目錄為 store
在 store 下分別創(chuàng)建4個(gè)js文件 actions.js , index.js , mutation-types.js , mutations.js
看名字也就知道這4個(gè)分別是做啥用的了,建議大家多閱讀閱讀 vuex 的文檔,多姿勢(shì)多動(dòng)手實(shí)踐,慢慢的也就能理解了。
// src/store/index.jsimport Vue from 'vue'import Vuex from 'vuex'Vue.use(Vuex);// 先寫(xiě)個(gè)假數(shù)據(jù)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日完善,陪女朋友一起過(guò)圣誕節(jié)需要6個(gè)小時(shí)' }]};export default new Vuex.Store({ state,})由于新增了頁(yè)面和store 在我們的入口js文件里配置下
// src/main.jsimport 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 路由下看見(jiàn)這樣的頁(yè)面
通過(guò) vue-Devtools 我們可以發(fā)現(xiàn)我們的store已經(jīng)構(gòu)造好了并且成功從store獲取了數(shù)據(jù)
創(chuàng)建任務(wù)組件
這個(gè)比較簡(jiǎn)單我們直接給出代碼
// 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>時(shí)間</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>這個(gè)組件很簡(jiǎn)單就3個(gè)input輸入而已,然后就兩個(gè)按鈕,保存我們就把數(shù)據(jù)push進(jìn)我們store的列表里
LogTime 屬于我們 TimeEntries 組件的一個(gè)子路由,所以我們依舊需要配置下我們的路由,并且利用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中廢除了使用事件的方式進(jìn)行通信,所以在小項(xiàng)目中我們可以使用Event Bus,其余最好都使用vuex,本文我們使用Vuex來(lái)實(shí)現(xiàn)數(shù)據(jù)通信
相信你剛剛已經(jīng)看見(jiàn)了我寫(xiě)了很多 this.$store.dispatch('savePlan', plan) 類(lèi)似這樣的代碼,我們?cè)俅谓y(tǒng)一說(shuō)明。
仔細(xì)思考一下,我們需要兩個(gè)全局?jǐn)?shù)據(jù),一個(gè)為所有計(jì)劃的總時(shí)間,一個(gè)是計(jì)劃列表的數(shù)組。
src/store/index.js 沒(méi)啥太多可介紹的,其實(shí)就是傳入我們的 state , mutations, actions 來(lái)初始化我們的Store。如果有需要的話我們還可能需要?jiǎng)?chuàng)建我們的 getter在本例中就不用了。
接著我們看 mutation-types.js ,既然想很明確了解數(shù)據(jù),那就應(yīng)該有什么樣的操作看起,當(dāng)然這也看個(gè)人口味哈
// src/store/mutation-types.js// 增加總時(shí)間或者減少總時(shí)間export const ADD_TOTAL_TIME = 'ADD_TOTAL_TIME';export const DEC_TOTAL_TIME = 'DEC_TOTAL_TIME';// 新增和刪除一條計(jì)劃export const SAVE_PLAN = 'SAVE_PLAN';export const DELETE_PLAN = 'DELETE_PLAN';// src/store/mutations.jsimport * as types from './mutation-types'export default { // 增加總時(shí)間 [types.ADD_TOTAL_TIME] (state, time) { state.totalTime = state.totalTime + time }, // 減少總時(shí)間 [types.DEC_TOTAL_TIME] (state, time) { state.totalTime = state.totalTime - time }, // 新增計(jì)劃 [types.SAVE_PLAN] (state, plan) { // 設(shè)置默認(rèn)值,未來(lái)我們可以做登入直接讀取昵稱(chēng)和頭像 const avatar = 'https://sfault-avatar.b0.upaiyun.com/147/223/147223148-573297d0913c5_huge256'; state.list.push( Object.assign({ name: '二哲', avatar: avatar }, plan) ) }, // 刪除某計(jì)劃 [types.DELETE_PLAN] (state, idx) { state.list.splice(idx, 1); }};最后對(duì)應(yīng)看我們的 actions 就很明白了
// src/store/actions.jsimport * 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 其實(shí)就是去觸發(fā)事件和傳入?yún)?shù)啦
加了這三個(gè)文件后我們的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) 當(dāng)執(zhí)行了這樣的方法就會(huì)調(diào)用 actions.js 里的 savePlan 方法,而 savePlan 又會(huì)觸發(fā) mutations 里的 types.SAVE_PLAN 最后修改數(shù)據(jù)視圖更新
PS:在這有個(gè)技巧就是,在 mutations 里都是用大寫(xiě)下劃線連接,而我們的 actions 里都用小寫(xiě)駝峰對(duì)應(yīng)。
個(gè)人理解這其實(shí)就是一個(gè)發(fā)布訂閱的模式
mutation-types 記錄我們所有的事件名
mutations 注冊(cè)我們各種數(shù)據(jù)變化的方法
actions 則可以編寫(xiě)異步的邏輯或者是一些邏輯,再去 commit
我們的事件
如果有 getter 我們可以把一些需要處理返回的數(shù)據(jù)放在這即可,不進(jìn)行業(yè)務(wù)操作
最后別忘了在我們的 main.js 里使用我們的 store
// src/store/main.jsimport store from './store'// ...var app = new Vue({ el: '#app', router, store, ...App,});開(kāi)始體驗(yàn)下你自己的任務(wù)計(jì)劃板吧!
最后
通過(guò)本文,我們可以學(xué)習(xí)到許多關(guān)于vue的特性。
1.了解了vue-cli腳手架
2.初步對(duì)webpack有了一些了解和認(rèn)識(shí)
3.如何用.vue愉快的開(kāi)發(fā)
4.使用vuex進(jìn)行組件通信
5.路由(子路由)的應(yīng)用
6.使用 vue-devtools 觀察我們的數(shù)據(jù)
個(gè)人網(wǎng)站 : http://www.meckodo.com
github地址: https://github.com/MeCKodo/vu...
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持武林網(wǎng)。
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注