藉助 Vue 來構建單頁面應用

(1/2)Vue構建單頁應用最佳實戰

前言

咱們將會選擇使用一些vue周邊的庫javascript

1.使用node.js後臺,瞭解到如何獲取數據php

2.實現單頁路由css

3.實現HTTP請求咱們的nodehtml

4.單項數據流前端

5.使用.vue文件進行開發vue

最終咱們將會構建出一個小demo,不廢話,直接上圖。java

安裝

1.咱們將會使用webpack去爲咱們的模塊打包,預處理,熱加載。若是你對webpack不熟悉,它就是能夠幫助咱們把多個js文件打包爲1個入口文件,而且能夠達到按需加載。這就意味着,咱們不用去擔憂因爲太多的組件,致使了過多的HTTP請求,這是很是有益於產品體驗的。但,咱們並不僅是爲了這個而使用webpack,咱們須要用webpack去編譯.vue文件,若是沒有使用一個loader去轉換咱們.vue文件裏的style,js,html,那麼瀏覽器就沒法識別。node

2.模塊熱加載是webpack的一個很是碉堡的特性,將會爲咱們的單頁應用帶來極大的便利。 一般來講,當咱們修改了代碼刷新頁面,那應用裏的全部狀態就都沒有了。這對於開發一個單頁應用來講是很是痛苦的,由於須要從新在跑一遍流程。若是有模塊熱加載,當你修改了代碼,你的代碼會直接修改,頁面並不會刷新,因此狀態也會被保留。jquery

3.Vue也爲咱們提供了CSS預處理,因此咱們能夠選擇在.vue文件裏寫LESS或者SASS去代替原生CSS。webpack

4.咱們過去一般須要使用npm下載一堆的依賴,可是如今咱們能夠選擇Vue-cli。這是一個vue生態系統中一個偉大創舉。這意味着咱們不須要手動構建咱們的項目,而它就能夠很快地爲咱們生成。

首先,安裝vue-cli。(確保你有node和npm)

npm i -g vue-cli

而後建立一個webpack項目而且下載依賴

vue init webpack vue-time-tracker cd vue-time-tracker npm i

接着使用 npm run dev 在熱加載中運行咱們的應用

這一行命令表明着它會去找到 package.json 的 scripts 對象,執行 node bulid/dev-server.js 。在這文件裏,配置了Webpack,會讓它去編譯項目文件,而且運行服務器,咱們在 localhost:8080 便可查看咱們的應用。

這些都準備好後,咱們須要爲咱們的路由和XHR請求下載兩個庫,咱們能夠從vue的官網中找到他們。

npm i vue-resource vue-router --save

初始化(main.js)

查看咱們的應用文件,咱們能夠在src目錄下找到 App.vue 和 main.js 。在 main.js 文件中,咱們引入 Vue 和 App ,而且建立了一個vue的實例(由於在router這行引入了App組件 router.start(App, '#app') )

// src/main.js

import Vue from 'vue' import App from './App.vue' import Hello from './components/Hello.vue' import VueRouter from 'vue-router' import VueResource from 'vue-resource' //註冊兩個插件 Vue.use(VueResource) Vue.use(VueRouter) const router = new VueRouter() // 路由map router.map({ '/hello': { component: Hello } }) router.redirect({ '*': '/hello' }) router.start(App, '#app')

咱們還須要在 index.html 包裹下咱們的 <app></app>

//index.html

<div id="app"> <app></app> </div>

咱們的初始化就到這結束了,接下來讓咱們開始建立別的組件。

建立首頁 View

首先,咱們須要爲咱們的應用增長下bootstrap.css,爲了方便,在這就直接在頭部引入CDN。

<head> <meta charset="utf-8"> <title>計劃板</title> <link href="//cdn.bootcss.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"> </head>

接着在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><a v-link="'/home'">首頁</a></li> <li><a v-link="'/time-entries'">計劃列表</a></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 的切換就是經過這個標籤開始顯現的。

接着,咱們須要建立一個 Home.vue 做爲咱們的首頁

// src/components/Home.vue

<template> <div class="jumbotron"> <h1>任務追蹤</h1> <p> <strong> <a v-link="'/time-entries'">建立一個任務</a> </strong> </p> </div> </template>

既然咱們須要顯示Home,那就須要開始配置路由,這很簡單,只須要在 main.js 裏把 Hello.vue 換爲 Home.vue 便可

//...
router.map({
  '/Home': { component: Home } }) router.redirect({ '*': '/Home' })

建立 任務列表 View

在這個頁面,咱們須要去建立咱們的時間跟蹤列表。

PS:如今這個頁面沒有數據,以後咱們會在後臺配置

// src/components/TimeEntries.vue <template> <div> //`v-if`是vue的一個指令 //`$route.path`是當前路由對象的路徑,會被解析爲絕對路徑當 //`$route.path !== '/time-entries/log-time'`爲`true`是顯示,`false`,爲不顯示。 //v-link 路由跳轉地址 <button v-if="$route.path !== '/time-entries/log-time'" v-link="'/time-entries/log-time'" class="btn btn-primary"> 建立 </button> <div v-if="$route.path === '/time-entries/log-time'"> <h3>建立</h3> </div> <hr> //下一級視圖 <router-view></router-view> <div class="time-entries"> <p v-if="!timeEntries.length"><strong>尚未任何任務</strong></p> <div class="list-group"> //v-for 循環渲染 <a class="list-group-item" v-for="timeEntry in timeEntries"> <div class="row"> <div class="col-sm-2 user-details"> //`:src`屬性,這個是vue的屬性綁定簡寫`v-bind`能夠縮寫爲`:` 好比a標籤的`href`能夠寫爲`:href`而且在vue的指令裏就必定不要寫插值表達式了(`:src={{xx}}`),vue本身會去解析 <img :src="timeEntry.user.image" class="avatar img-circle img-responsive" /> <p class="text-center"> <strong> {{ timeEntry.user.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> {{ timeEntry.totalTime }} </h3> <p class="label label-primary text-center"> <i class="glyphicon glyphicon-calendar"></i> {{ timeEntry.date }} </p> </div> <div class="col-sm-7 comment-section"><p>{{ timeEntry.comment }}</p></div><div class="col-sm-1"><button class="btn btn-xs btn-danger delete-button"//事件綁定簡寫 @xxx @click="deleteTimeEntry(timeEntry)"> X </button></div></div></a></div></div></div></template>

關於template的解釋,都寫在一塊兒了,再看看咱們的 script

// src/components/TimeEntries.vue

<script> export default { data () { // 事先模擬一個數據 let existingEntry = { user: { name: '二哲', email: 'kodo@forchange.cn', image: 'https://sfault-avatar.b0.upaiyun.com/888/223/888223038-5646dbc28d530_huge256' }, comment: '個人一個備註', totalTime: 1.5, date: '2016-05-01' } return { timeEntries: [existingEntry] } }, methods: { deleteTimeEntry (timeEntry) { //這個方法用於刪除某一項計劃 let index = this.timeEntries.indexOf(timeEntry) if (window.confirm('肯定要刪除嗎?')) { this.timeEntries.splice(index, 1) //這裏會派發到父組件上,執行父組件events裏的deleteTime方法 this.$dispatch('deleteTime', timeEntry) } } }, events: { timeUpdate (timeEntry) { this.timeEntries.push(timeEntry) //繼續向上派發 return true } } } </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>

因爲新增了頁面,因此咱們繼續配置咱們的路由

// src/main.js

import TimeEntries from './components/TimeEntries.vue' //... router.map({ '/home': { component: Home }, '/time-entries': { component: TimeEntries } }) //...

建立任務組件

這個比較簡單咱們直接給出代碼

// 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="timeEntry.date" placeholder="Date" /> </div> <div class="col-sm-6"> <label>時間</label> <input type="number" class="form-control" v-model="timeEntry.totalTime" placeholder="Hours" /> </div> </div> <div class="form-group"> <div class="col-sm-12"> <label>備註</label> <input type="text" class="form-control" v-model="timeEntry.comment" placeholder="Comment" /> </div> </div> <button class="btn btn-primary" @click="save()">保存</button> <button v-link="'/time-entries'" class="btn btn-danger">取消</button> <hr> </div> </template> <script> export default { data () { return { //模擬一個默認值 timeEntry: { user: { name: '二哲', email: 'kodo@forchange.cn', image: 'https://sfault-avatar.b0.upaiyun.com/888/223/888223038-5646dbc28d530_huge256' } } } }, methods: { save () { let timeEntry = this.timeEntry this.$dispatch('timeUpdate', timeEntry) this.timeEntry = {} } } } </script>

這個組件很簡單就3個input輸入而已,而後就兩個按鈕,保存咱們就把數據push進咱們的列表裏,而且初始化咱們的timeEntry。取消的話,咱們就路由定位到 /time-entries 便可。

ps:按理來講咱們應該是要填寫6個數據包括名字,郵箱和頭像。但這裏爲了演示就暫時先這樣。之後結合後臺咱們會繼續完善這裏。

LogTime 屬於咱們 TimeEntries 組件的一個子路由,因此咱們依舊須要配置下咱們的 router.map

// src/main.js

import LogTime from './components/LogTime.vue' //... router.map({ '/home': { component: Home }, '/time-entries': { component: TimeEntries, subRoutes: { '/log-time': { component: LogTime } } } }) //...

建立側邊欄組件

目前咱們首頁左側還有一塊空白,咱們須要它放下一個側邊欄去統計全部計劃的總時間。

// src/App.vue

  //...

  <div class="container"> <div class="col-sm-3"> <sidebar :time="totalTime"></sidebar> </div> <div class="col-sm-9"> <router-view></router-view> </div> </div> //...

因爲咱們把總時間存放在最上級的父組件上,因此咱們須要把咱們的總時間傳入咱們的 sidebar 組件。

在寫下咱們的兩個時間計算方法

<script> import Sidebar from './components/Sidebar.vue' export default { components: { 'sidebar': Sidebar }, data () { return { totalTime: 1.5 } }, events: { timeUpdate (timeEntry) { this.totalTime += parseFloat(timeEntry.totalTime) }, deleteTime (timeEntry) { this.totalTime -= parseFloat(timeEntry.totalTime) } } } </script>

最後給出咱們 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 { props: ['time'] } </script>

props 就是vue中傳值的寫法,不只要在咱們自定義的標籤上傳入 <sidebar :time="totalTime"></sidebar> ,還須要在組件裏js裏定義 props: ['time']

最後

本章,咱們能夠學習到許多關於vue的特性。

1.瞭解了vue-cli腳手架

2.初步對webpack有了一些瞭解和認識

3.如何用.vue愉快的開發

4.父子組件通訊

5.路由(子路由)的應用

下一章,咱們將會結合node學習vue-resource,更好的完善咱們SPA應用

番外篇

我看不少人都不知道如何引入bootstrap,我就在這加了一下

首先npm i jquery bootstrap style-loader --save-dev;

而後我修改了兩個文件 第一個是 webpack.base.conf.js 我把module都改了

最後咱們在入口js文件里加三行代碼

import 'jquery' import 'bootstrap/dist/css/bootstrap.css' import 'bootstrap/dist/js/bootstrap'

在npm run dev 看看頁面吧! 在head裏會有一個style全是bootstrap的代碼.別忘了把index.html裏的第三方bootstrap註釋了.

在我此次更新的代碼裏,我已經把引用第三方代碼刪了.

(2/2)Vue構建單頁應用最佳實戰

前言

本章節,將會把全部的請求全寫爲跨域請求。不知道爲何,不少人一用了框架就會不知所措。給你們一個忠告,享受框架帶來的便利,別忘了時刻提醒本身學好基礎知識。

先把一些沒必要要的代碼刪了。

//TimeEntries.vue 的模擬數據代碼
data () {
  // 模擬下初始化數據 /*let existingEntry = {  comment: '個人第一個任務',  totalTime: 1.5,  date: '2016-05-01'  }*/ return { timeEntries: [] } }, //頭像和暱稱暫時寫死 <div class="col-sm-2 user-details"> <img src="https://avatars1.githubusercontent.com/u/10184444?v=3&s=460" class="avatar img-circle img-responsive" /> <p class="text-center"> <strong> 二哲 </strong> </p> </div> //LogTime.vue裏的模擬數據代碼 data () { return { timeEntry: { /*user: {  name: '二哲',  email: 'kodo@forchange.cn',  image: 'https://sfault-avatar.b0.upaiyun.com/888/223/888223038-5646dbc28d530_huge256'  },*/ } } },

咱們將專一3個字段的增刪改查,任務時間,持續時間,備註。

正文

咱們的數據交互其實很簡單,因此我在這選擇使用你們最熟悉的 express 和 mongodb ,在一個 app.js 文件裏完成全部的 controller 。

首先,安裝幾個必要的包 npm i express mongodb morgan body-parser --save-dev;

簡單解釋下Morgan和body-parser,其實就是一個log美化和解析參數。具體你們能夠google下。

在咱們的根目錄下,建立 app.js 初始化如下代碼

//app.js
var express = require('express'); var app = express(); var bodyParser = require('body-parser'); var morgan = require('morgan'); var MongoClient = require('mongodb').MongoClient; var mongoUrl = 'mongodb://localhost:27017/mission'; var _db; app.use(morgan('dev')); app.use(bodyParser.json()); app.use(express.static('dist')); MongoClient.connect(mongoUrl, function (err, db) { if(err) { console.error(err); return; } console.log('connected to mongo'); _db = db; app.listen(8888, function () { console.log('server is running...'); }); });

解釋下mongoUrl這行 mongodb://localhost:27017/mission 鏈接相應的端口,而且使用mission表。此時你是沒有 mission 數據庫的,這不用在乎。在咱們後續操做中,它將會自動建立一個mission數據庫。

上面代碼的意思是,咱們建立咱們的一個mongo鏈接,當數據庫鏈接上了後再啓動咱們的服務器。

接着先啓動咱們的mongo服務。在命令行裏 sudo mongo 。

若是你用得是webstrom編輯器,能夠直接運行 app.js ,若是是命令行,那就使用 node app.js

若是看見命令行輸出了 connected to mongo server is running... 就能夠在 8888 端口訪問咱們的應用了。(在這以前別忘了build你的代碼)

因爲咱們講得是跨域,因此咱們講在咱們的dev環境下完成全部的請求。 npm run dev

關閉咱們的8888端口頁面,進入8080端口的開發環境。

寫下咱們第一個建立任務的請求。

//app.js

//使用post方法 app.post('/create', function(req, res, next) { //接收前端發送的字段 var mission = req.body; //選擇一個表my_mission 此時沒有不要緊,也會自動建立 var collection = _db.collection('my_mission'); //若是咱們須要的字段不存在,返回前端信息 if(!mission.comment || !mission.totalTime || !mission.date) { res.send({errcode:-1,errmsg:"params missed"}); return; } //若是存在就插入數據庫,返回OK collection.insert({comment: mission.comment, totalTime: mission.totalTime,date:mission.date}, function (err, ret) { if(err) { console.error(err); res.status(500).end(); } else { res.send({errcode:0,errmsg:"ok"}); } }); });

修改下咱們的 LogTime.vue

//LogTime.vue
<button class="btn btn-primary" @click="save()">保存</button> methods: { save () { this.$http.post('http://localhost:8888/create',{ comment : this.timeEntry.comment, totalTime : this.timeEntry.totalTime, date : this.timeEntry.date }).then(function(ret) { console.log(ret); let timeEntry = this.timeEntry console.log(timeEntry); this.$dispatch('timeUpdate', timeEntry) this.timeEntry = {} }) } }

輸入好內容,點擊保存按鈕,會發現報了個錯。這其實就是最多見的跨域請求錯誤。

可是咱們明明寫得是 post 請求爲何顯示得是 options 呢?

這實際上是跨域請求前會先發起的一個 options 請求,須要先問問服務端,我須要一些操做能夠嗎?若是服務端那裏是容許的,纔會繼續讓你發送 post 請求。

我不知道那些使用 vue-resource 各類姿式也想知足跨域請求的人是怎麼想的。想上天嗎?

因此咱們須要服務端配置,而不是前端。

//app.js
app.all("*", function (req, res, next) { res.header('Access-Control-Allow-Origin', '*'); res.header("Access-Control-Allow-Headers", "Content-Type,Content-Length, Authorization, Accept,X-Requested-With"); res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS"); if (req.method == 'OPTIONS') { res.send(200); } else { next(); } });

Access-Control-Allow-Origin 是設置你的來源域名,寫 * 是很危險的操做。因此咱們能夠直接寫成咱們所需的域名和端口,別人就無法請求了。

另外幾行就不解釋了,一看就懂。

不出意外,能夠發現發送了options後,立刻發送了post,而後就建立成功了。看下mongo的表,也多了一條記錄。

接着來讓咱們一口氣寫完剩下的三個請求。列表渲染,刪除計劃,獲取總時長。

//app.js
var ObjectID = require('mongodb').ObjectID //獲取總時長 app.get('/time', function(req, res, next) { //獲取數據表 var collection = _db.collection('my_mission'); var time = 0; //查詢出全部計劃 collection.find({}).toArray(function (err, ret) { if(err) { console.error(err); return; } //全部計劃累加時長 ret.forEach(function (item, index) { time += +item.totalTime; }); //返回時長 res.json({errcode:0,errmsg:"ok",time:time}); }); }); //獲取列表 app.get('/time-entries', function(req, res, next) { var collection = _db.collection('my_mission'); collection.find({}).toArray(function (err, ret) { if(err) { console.error(err); return; } res.json(ret); }); }); //刪除計劃 app.delete('/delete/:id', function (req, res, next) { var _id = req.params.id; var collection = _db.collection('my_mission'); console.log(_id) //使用mongodb的惟一ObjectId字段查找出對應id刪除記錄 collection.remove({_id: new ObjectID(_id)} ,function (err, result) { if(err) { console.error(err); res.status(500).end(); } else { res.send({errcode:0,errmsg:"ok"}); } }); });

前端部分

//App.vue
ready() {
    this.$http.get('http://localhost:8888/time') .then(function(ret) { this.totalTime = ret.data.time; }) .then(function(err) { console.log(err); }) },
//TimeEntries.vue
route : {
  data(){
    this.$http.get('http://localhost:8888/time-entries') .then(function(ret) { this.timeEntries = ret.data; }) .then(function(err) { console.log(err); }) } },
//TimeEntries.vue
<div class="col-sm-1"> <button class="btn btn-xs btn-danger delete-button" @click="deleteTimeEntry(timeEntry)"> X </button> </div> deleteTimeEntry (timeEntry) { // 刪除 let index = this.timeEntries.indexOf(timeEntry) let _id = this.timeEntries[index]._id if (window.confirm('確認刪除?')) { this.$http.delete('http://localhost:8888/delete/' + _id) .then(function(ret) { console.log(ret); }) .then(function(err) { console.log(err) }); this.timeEntries.splice(index, 1) this.$dispatch('deleteTime', timeEntry) } }

完結

到此,咱們就將咱們整個應用完成了。新增建立刪除均可用了。

原本還想有上傳頭像等,那樣以爲更多的是偏後端教學。既然咱們是vue的簡單入門教程就不過多介紹。

本系列讓你們輕鬆的瞭解學習了vue,vue-router,vue-resource,express,mongodb的運用。

仍是那句話,享受框架帶來便利的同時,別忘了增強基礎的訓練。基本功纔是真正的王道啊。玩電競的玩家必定深有體會。

最後給有興趣的同窗留下兩個簡單的做業 1.完成頭像暱稱的字段 2.完成修改操做

源碼地址: https://github.com/MeCKodo/vue-tutorial

相關文章
相關標籤/搜索