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';


