Vue 實現(xiàn) Ajax請求 和跨域請求主要是通過插件vue-resource.js。
引進
引進插件vue-resource.js的方式主要有以下三種:
- 將插件vue-resource.js文件下載到本地秉撇,通過script引進墓贿。
- 在網(wǎng)站http://www.bootcdn.cn/vue-resource/選擇插件版本,通過script引進娩梨。
- 如果項目是通過 webpack 構建的,可以在項目文件中安裝插件,然后引進滤奈。實現(xiàn)如下:
// 安裝命令
npm install vue-resource --save
// 引進
import VueResource from 'vue-resource'
發(fā)送請求
實現(xiàn)發(fā)送請求的方式有兩種:
- 全局方式:Vue.http.get(...)
- Vue 實例內(nèi)部(放在 methods 內(nèi)):this.$http.get(...)
返回結果
發(fā)送請求后,響應返回的是 Promise 對象撩满。
// 全局
Vue.http.get(url).then(response => {
... // response級請求后返回的對象
}).catch(function(err){
...
})
// 實例內(nèi)部
this.$http.get(url).then(response => {
...
}).catch(function(err){
...
})
上面例子蜒程,通過get方式向url請求數(shù)據(jù),然后將請求結果返回伺帘,返回結果是一個 Promise 對象昭躺。
相關參數(shù)
發(fā)送請求可以攜帶一些參數(shù),一個完整的請求語句如下:
this.$http.requestType(url, [body],[config]).then(successCallback, errorCallback)
或者
Vue.http.requestType(url, [body],[config]).then(successCallback, errorCallback)
requestType:請求類型
不同請求類型包含的參數(shù)不同伪嫁,請求的類型主要有:
- get(url, [config])
- head(url, [config])
- delete(url, [config])
- jsonp(url, [config])
- post(url, [body], [config])
- put(url, [body], [config])
- patch(url, [body], [config])
參數(shù)選項
主要的參數(shù)選項有:
- url:請求的地址领炫。
- body:作為請求主體發(fā)送的數(shù)據(jù)。
- header:請求的 HTTP 頭部张咳。
- params:請求數(shù)據(jù)帝洪,是一個對象。
- timeout:響應時間脚猾。
- before:發(fā)送請求之前的回調(diào)函數(shù)葱峡。
- uploadProgress:上傳事件的函數(shù)。
- downloadProgress:下載事件的函數(shù)龙助。
響應返回對象
當請求成功后砰奕,會返回一個 Promise 對象。
這個對象中主要包含以下這些屬性:
- url:響應的 URL 地址提鸟。
- body:響應主體军援,主要類型有:Object/Blob/string。
- Headers:響應頭部對象称勋。
- ok:布爾值胸哥, 是否響應成功。
- status:2 開頭表示請求成功铣缠,主要是 200~299烘嘱。
- statusText:響應狀態(tài)的短語昆禽。
這個對象中主要包含以下這些方法:
- text():類型是 Promise,將請求的 body 主體轉化為 string 類型蝇庭。
- json():類型是 Promise醉鳖,將請求的 body 主體解析為 JSON 對象。
- blob():類型是 Promise哮内,將請求的 body 主體轉化為 Blob 對象盗棵。主要是用于請求一些圖片的相關信息,如:圖片類型北发,大小等纹因。
例子(請求數(shù)據(jù)、請求圖片信息琳拨、jsonp 實現(xiàn)跨域請求)
實例 1(請求數(shù)據(jù))
需求:請求本地文件中的數(shù)據(jù)瞭恰,加載都頁面上。
主要代碼如下:
<div id="app">
<button type="button" @click="ajaxRequest">button</button>
<p v-for = "(value, key) of msg">{{ key }} ---- {{ value }}</p>
</div>
<script src="../vue.js"></script>
<script src="https://cdn.bootcss.com/vue-resource/1.5.0/vue-resource.min.js"></script>
<script>
new Vue({
el: "#app",
data: {
msg: {
Url: '',
Body: '',
Status: '',
StatusText: '',
},
url: './data.txt'
},
methods: {
ajaxRequest: function () {
this.$http.get(this.url)
.then(response => {
this.msg.Url = response.url // 響應地址
this.msg.Body = response.body // 響應主體
this.msg.Status = response.status // 響應狀態(tài)
this.msg.StatusText = response.statusText // 響應狀態(tài)短語
}).catch(function (err) {
alert("Error", err)
})
}
}
})
</script>
效果如下:
實例 2(請求圖片信息)
需求:請求圖片的相關數(shù)據(jù)狱庇,加載都頁面上惊畏。
具體代碼如下:
<div id="app">
<button type="button" @click="ajaxFun">button</button>
<img :src="img" alt="picture">
<p v-for = "(value, key) of imgInfo">{{ key }} :: {{ value }}</p>
</div>
<script src="../vue.js"></script>
<script src="https://cdn.bootcss.com/vue-resource/1.5.0/vue-resource.min.js"></script>
<script>
let app = new Vue({
el: '#app',
data: {
iShow: true,
msg: '',
img: './rocket.jpg',
imgInfo: {
type: '',
size: ''
}
},
methods: {
// 獲取圖片的信息
ajaxFun: function () {
this.$http.get(this.img, {
responseType: 'blob'
}).then((response) => {
return response.blob() // 異步請求圖片的resolve狀態(tài)返回給blob
}).then(blob => { // blob處理
this.imgInfo.type = blob.type
this.imgInfo.size = blob.size
}).catch(function (e) { // 錯誤捕獲
alert(e)
})
}
}
})
</script>
效果如下:
實例 3(jsonp 實現(xiàn)跨域請求)
需求:百度輸入框搜索:aurora,本地實現(xiàn)跨域請求數(shù)據(jù)密任。
- 輸入 aurora
- 找到要跨域請求數(shù)據(jù)的鏈接
- 雙擊打開鏈接颜启,查看數(shù)據(jù)
- 實現(xiàn)代碼
<div id="app">
<button type="button" @click="jsonpRequest">button</button>
<p v-for="(value, key) of msg">
{{ key }} :: {{ value }}
</p>
</div>
<script src="../vue.js"></script>
<script src="https://cdn.bootcss.com/vue-resource/1.5.0/vue-resource.min.js"></script>
<script>
function __jsonp21__(data) {
console.log(data);
}
new Vue({
el: '#app',
data: {
msg: {
status: '',
info: []
}
},
methods: {
jsonpRequest: function () {
this.$http.jsonp(
'https://sp1.baidu.com/5b11fzupBgM18t7jm9iCKT-xh_/sensearch?wd=aurora&cb=bd_cb_dict3_1521617356074&callback=bd_cb_dict3_1521617356074&_=1521617355798', {
jsonp: 'cb' // 指定jsonp回調(diào)函數(shù)名稱
}
).then(response => {
console.log(response.body);
let res = response.body
this.msg.status = res.err_msg
this.msg.info = res.liju_result
})
}
}
})
</script>
注意:this.$http.jsonp()的第二個參數(shù){...}用于指定參數(shù)和回調(diào)函數(shù)的名稱。如果要傳遞參數(shù)給地址浪讳,則參數(shù)的具體形式為:params:{...}
實現(xiàn)效果: