Vue 2.0 入门系列(10)Vue Ajax 的简单使用(with Laravel)
发布时间:2020-12-16 03:27:45 所属栏目:百科 来源:网络整理
导读:本节将简单介绍如何使用 Ajax 与 Laravel 进行通信。首先,创建一个 Laravel 应用: $ laravel new ajxa-with-laravel 我们以 Get 请求为例,返回任务列表,简单定义 get 请求的返回: /routes/web.phpRoute::get('tasks',function () { return ['编程','家
本节将简单介绍如何使用 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('/user?ID=12345') .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); }); 接下里就可以在 var vm = new Vue({ el:'#root',data:{ tasks:[] },mounted(){ axios.get('/tasks') .then(function (response) { vm.tasks = response.data; }) } }); 使用 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> 为了让 最后,可以对 /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); } });
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |