Vueで非同期通信
Ajax的な動作をさせる場合、Axiosというライブラリでできるっぽい。 (プレーンなjsの場合async/awaitを使う?)
例)
axiosをlarabelのbladeやvueで利用する場合
<script> export default { // 略・・・ // データ data: function () { return { req: {}, // htmlのinputとかと連携させておいたりする res: {}, // post結果取得用 }; }, // 関数 methods: { /** * なにかのボタンクリック時 */ click: function () { // サーバ処理 axios .post("htpps://localhost/hoge", this.req) .then( function (response) { console.log(response); // リクエスト受け取り this.res = response.data; }.bind(this) ) .catch(function (error) { console.log(error); }); } }; </script>
axios.postの引数はurlと渡す値。戻り値はPromiseオブジェクト。
Promiseオブジェクトではthenには成功時のコールバック関数、catchはエラー時のコールバック関数を引数として与える。
関数オブジェクトにbindで、関数内にて使用されるthisの値を指定することができる。
例ではコールバック関数内のthisがvueオブジェクトになっている。