Vue 2.0入門シリーズ(10)Vue Ajaxの簡単な使用(with Laravel)

2241 ワード

このセクションでは、Ajaxを使用してLaravelと通信する方法について簡単に説明します.まず、Laravelアプリケーションを作成します.
$ laravel new ajxa-with-laravel

Getリクエストを例にとると、タスクリストに戻り、getリクエストの戻りを簡単に定義します.
/routes/web.php
Route::get('tasks', function () {
    return ['  ','  ','  ','  '];
});

ビューファイルを編集し、関連ライブラリを導入するには、次の手順に従います.
/resources/views/welcome.blade.php



    
    Document


    

Vue はルーティング を っていないので、サードパーティのライブラリを することができます.ここではaxiosを し、getリクエストを する は の りです.
axios.get('/user?ID=12345')
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

に、app.jsでVueインスタンスを できます.
var vm = new Vue({
    el:'#root',
    data:{
        tasks:[]
    },
    mounted(){
        axios.get('/tasks')
        .then(function (response) {
            vm.tasks = response.data;
        })
    }
});
then を する 、thisはグローバルオブジェクトwindowを すため、 のように くことはできません.
this.tasks = response.data;

vueインスタンスを す は、 の き を します.
mounted(){
    axios.get('/tasks')
        .then(response => this.tasks = response.data);
}

に、ビューにタスクのリストを します.
/resources/views/welcome.blade.php
  • @{{ task }}
{{ }}がLaravelの フラグに されないように、@を に する がある.
に、axiosを にカプセル することができる.
/public/js/app.js
Vue.prototype.$http = axios;

var vm = new Vue({
    el:'#root',
    data:{
        tasks:[]
    },
    mounted(){
        this.$http.get('/tasks')
            .then(response => this.tasks = response.data);
    }
});
  • axios トップページ
  • の -ECMAScript 6