初識vue 2.0(3):Ajax請求

來源:互聯網
上載者:User

標籤:exports   介面   引入   string   web程式   method   com   ima   host   

0,類比ajax請求,需要構建web程式,使用express 方便快捷。

1,安裝express 構建web server:

npm install -g expressnpm install -g express-generator

2,建立 express 項目:

express myservercd myservernpm install 

3,啟動項目,一般情況下可以使用:

npm start

但開發環境需要監控代碼變動並自動重啟進程,因此需要安裝 supervisor。

npm install -g supervisor

使用supervisor啟動:

supervisor ./bin/www

為了方便管理,在項目根目錄下建立start.bat啟動指令碼。

start supervisor ./bin/www

4,修改express 預設router目錄中的users.js,將請求的get參數,轉換成json直接返回 ^_^

var express = require(‘express‘);var router = express.Router();/* GET users listing. */router.get(‘/‘, function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");//解決跨域問題 res.end(JSON.stringify(req.query));});module.exports = router;

至此,web server打架完畢,可以提供簡單的資料介面服務,效果如下:

5,構建前端ajax請求,安裝 axiso:

npm install -save axios

6,在main.js 中引入:

import axios from ‘axios‘Vue.prototype.$ajax = axios

7,重寫Game模組:

export default {  name: ‘game‘,  data () {    return {      msg: ‘‘    }  },  mounted:function(){this.getData()  },  methods:{getData:function(){var _this = this;this.$ajax.get(‘http://localhost:3000/users?username=tree&password=123456‘).then(function(response) {console.log(response.data);_this.msg="我是Game模組,使用者名稱:"+response.data.username});}  }}

啟動前端開發模式,可以觀察到瀏覽器network中有介面請求,顯示效果如下:

 

 

當然,這隻是個demo ,下一篇我們來講解一下事件 ^_^

 

初識vue 2.0(3):Ajax請求

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.