1. 程式人生 > 實用技巧 >Vue中傳送HTTP請求

Vue中傳送HTTP請求

Vue中傳送HTTP請求

HTTP庫:

vue-resource:https://github.com/pagekit/vue-resource

axios:http://www.axios-js.com/

前言

設定請求的根目錄

前言

Vue中並沒有直接提供對HTTP請求模組的封裝,而是以使用一個單獨的外掛去封裝了HTTP的模組,vue-resource是vue提供的一個外掛,除此之外你還可以使用其它的外掛比如axios。

<script src="../lib/vue-2.4.0.js"></script>

    <!-- vue-resource依賴於vue,它只是在Vue的this上擴充套件了$http-->
    <script src="../lib/vue-resource-1.3.4.js"></script>
</head>

<body>
<div id="app">
    <input type="button" value="get請求" @click="getInfo">
    <input type="button" value="post請求" @click="postInfo">
    <input type="button" value="jsonp請求" @click="jsonpInfo">
</div>

<script>
    var
vm = new Vue({ el: '#app', data: {}, methods: { getInfo() { // 這裡如果使用webstrom啟動訪問會報錯,因為這是跨源訪問,所以 // 按理說應該是在源網站上訪問該頁面 this.$http.get('http://vue.studyit.io/api/getlunbo') .then((success) => { console.log(success); }, (error)
=> { console.log(error); }) }, postInfo() { // 發起 post 請求 application/x-wwww-form-urlencoded // 手動發起的 Post 請求,預設沒有表單格式,所以,有的伺服器處理不了 // 通過 post 方法的第三個引數, { emulateJSON: true } 設定 提交的內容型別 為 普通表單資料格式 this
.$http.post('http://vue.studyit.io/api/post', {}, {}) .then(success => { console.log(success); }) // error可以省略 }, jsonpInfo() { this.$http.jsonp('http://vue.studyit.io/api/jsonp') .then(result => { console.log(result); }) } } }) </script>

設定請求的根目錄

vue-resource的文件裡有Configuration項,在其中有說明。

// main.js中

// http請求
import VueResource from 'vue-resource'
Vue.use(VueResource)
// 設定全域性http請求根路徑[最後不帶/,在請求時之前也不能帶/]
Vue.http.options.root = 'http://vue.studyit.io';