Axios---Vueがリクエストを送信するためのkalrry
1.はじめに
Vue-resourceは、Vueに付属するリクエストを送信する方法です
。Axiosは、完了するためのサードパーティのプラグインです。
- Vue自体はAxiosリクエストの送信をサポートしていません。これは、vue-resource(vue1.0バージョン)、axios(vue2.0バージョン)などのプラグインを使用して実装する必要があります。
- axiosは、リクエストを送信するためのPromiseベースのHTTPリクエストクライアントです。これもvue2.0で公式に推奨されており、vue-resourceを更新および維持しなくなりました。
- 参照:GitHubでaxiosを検索し、APIドキュメントを表示します
2.アクシオス
対応するjsファイルを紹介します。オンラインで使用できます
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
1.GETリクエスト
例1:JSONデータを読み取るだけで、response.dataを使用してJSONデータを読み取る
json
<div id="app">
<button @click="showMessage()">查看test.txt文本内容</button>
</div>
<script type="text/javascript">
window.onload = function() {
new Vue({
el: '#app',
methods: {
showMessage: function() {
axios.get('test.json').then(function(response) {
console.log(response.data,typeof response.data)
}, function() {
alert("请求失败")
}).catch(function(error) {
console.log(error);
})
}
}
})
}
</script>
パラメータを渡すメソッドを取得します
1.パラメータをURLに直接追加します
2.パラメータを介してパラメータを設定します
// 直接在 URL 上添加参数 ID=12345
axios.get('/user?ID=12345')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
// 也可以通过 params 设置参数:
axios.get('/user', {
params: {
ID: 12345
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
3.パラメータを渡すPOST
axios.post('/user', {
firstName: 'Fred', // 参数 firstName
lastName: 'Flintstone' // 参数 lastName
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
3.足場での使用
axiosはAJAXリクエストを送信します
1. axiosをインストールし、紹介します
- npm install axios -S#axiosコンポーネントを直接ダウンロードします。ダウンロード後、axios.jsはnode_modules \ axios\distに保存されます。
- axios.min.jsファイルをインターネットから直接ダウンロードします
- スクリプトsrcでファイルをインポートする
- getリクエスト
を送信する基本的な形式
:形式1:axios([options])#この形式はすべてのデータをオプションに直接書き込みます。optionsは実際には辞書です
。形式2:axios.get(url [、options]);
2.パラメータ送信の方法:
- URLを介してパラメータを渡す
- paramsオプションを介してパラメータを渡します
3.AJAXリクエストを送信します
el:'#itany',
data:{
undefined
user:{
undefined
name:'alice',
age:19},
},
methods:{
undefined
send(){
undefined
axios({
undefined
method:'get',
url:'http://www.baidu.com?name=tom&age=23'}).then(function(resp){
undefined
console.log(resp.data);
}).catch(resp=>{
undefined
console.log('请求失败:'+resp.status+','+resp.statusText);
});
},
sendGet(){
undefined
axios.get('server.php',{
undefined
params:{
undefined
name:'alice',
age:19}
})
.then(resp=>{
undefined
console.log(resp.data);
}).catch(err=>{
//console.log('请求失败:'+err.status+','+err.statusText);
});
},
}
});
}