Vue 2.0 入门系列10Vue Ajax 的简单使用with Laravel)

本节将简单介绍如何使用 Ajax 与 Laravel 进行通信。首先,创建一个 Laravel 应用:

$ laravel new ajxa-with-laravel

我们以 Get 请求为例,返回任务列表,简单定义 get 请求的返回:

/routes/web.PHP
Route::get('tasks',function () {
    return ['编程','家务','编程','购物'];
});

编辑视图文件,引入相关库:

/resources/views/welcome.blade.PHP
<!DOCTYPE html>
<html lang="zh-cn">
<head>
    <Meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <div id="root">

    </div>

    <script src="https://cdn.bootcss.com/vue/2.2.6/vue.js"></script>
    <script src="https://cdn.bootcss.com/axios/0.16.1/axios.js"></script>
    <script type="text/javascript" src="/js/app.js"></script>
</body>
</html>

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
<div id="root">
  <ul v-for="task in tasks">
      <li>@{{ task }}</li>
  </ul>
</div>

为了让 {{ }} 不被解析成 Laravel 的输出标记,需要在前面添加 @

最后,可以对 axios 进行简单的封装:

/public/js/app.js
Vue.prototype.$http = axios;

var vm = new Vue({
    el:'#root',mounted(){
        this.$http.get('/tasks')
            .then(response => this.tasks = response.data);
    }
});

相关文章

IE6是一个非常老旧的网页浏览器,虽然现在很少人再使用它,但...
PHP中的count()函数是用来计算数组或容器中元素的个数。这个...
使用 AJAX(Asynchronous JavaScript and XML)技术可以在不...
Ajax(Asynchronous JavaScript and XML)是一种用于改进网页...
本文将介绍如何通过AJAX下载Excel文件流。通过AJAX,我们可以...
Ajax是一种用于客户端和服务器之间的异步通信技术。通过Ajax...