(2/2)Vue构建单页应用最佳实战

前言

本章节,将会把全部的请求全写为跨域请求。不知道为何,不少人一用了框架就会不知所措。给你们一个忠告,享受框架带来的便利,别忘了时刻提醒本身学好基础知识。前端

先把一些没必要要的代码删了。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个字段的增删改查,任务时间,持续时间,备注。node

正文

咱们的数据交互其实很简单,因此我在这选择使用你们最熟悉的expressmongodb,在一个app.js 文件里完成全部的controllergit

首先,安装几个必要的包npm i express mongodb morgan body-parser --save-dev;github

简单解释下Morgan和body-parser,其实就是一个log美化和解析参数。具体你们能够google下。web

在咱们的根目录下,建立app.js初始化如下代码vue-router

//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数据库。mongodb

上面代码的意思是,咱们建立咱们的一个mongo链接,当数据库链接上了后再启动咱们的服务器。数据库

接着先启动咱们的mongo服务。在命令行里 sudo mongoexpress

若是你用得是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
(1/2)Vue构建单页应用最佳实战http://www.javashuo.com/article/p-soegngmr-a.html国内最优秀的vue群:364912432

相关文章
相关标签/搜索