添加链接
link之家
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接

Vue 要实现异步加载需要使用到 vue-resource 库。

Vue.js 2.0 版本推荐使用 axios 来完成 ajax 请求。

<script src="https://cdn.staticfile.org/vue-resource/1.5.1/vue-resource.min.js"></script>

Get 请求

以下是一个简单的 Get 请求实例,请求地址是一个简单的 txt 文本:

window . onload = function ( ) { var vm = new Vue ( { el : ' #box ' , data : { msg : ' Hello World! ' , methods : { get : function ( ) { // 发送get请求 this .$ http . get ( ' /try/ajax/ajax_info.txt ' ) . then ( function ( res ) { document . write ( res . body ) ; } , function ( ) { console . log ( ' 请求失败处理 ' ) ; } ) ; } ) ; 尝试一下 » this.$http.get('get.php',{params : {a:1,b:2}}).then(function(res){ document.write(res.body); },function(res){ console.log(res.status);

post 发送数据到后端,需要第三个参数 {emulateJSON:true}

emulateJSON 的作用: 如果Web服务器无法处理编码为 application/json 的请求,你可以启用 emulateJSON 选项。

window . onload = function ( ) { var vm = new Vue ( { el : ' #box ' , data : { msg : ' Hello World! ' , methods : { post : function ( ) { // 发送 post 请求 this .$ http . post ( ' /try/ajax/demo_test_post.php ' , { name : " 菜鸟教程 " , url : " http://www.runoob.com " } , { emulateJSON : true } ) . then ( function ( res ) { document . write ( res . body ) ; } , function ( res ) { console . log ( res . status ) ; } ) ; } ) ; 尝试一下 »

demo_test_post.php 代码如下:

$name = isset($_POST['name']) ? htmlspecialchars($_POST['name']) : ''; $city = isset($_POST['url']) ? htmlspecialchars($_POST['url']) : ''; echo '网站名: ' . $name; echo "\n"; echo 'URL 地址: ' .$city;

语法 & API

你可以使用全局对象方式 Vue.http 或者在一个 Vue 实例的内部使用 this.$http来发起 HTTP 请求。

// 基于全局Vue对象使用http
Vue.http.get('/someUrl', [options]).then(successCallback, errorCallback);
Vue.http.post('/someUrl', [body], [options]).then(successCallback, errorCallback);
// 在一个Vue实例内使用$http
this.$http.get('/someUrl', [options]).then(successCallback, errorCallback);
this.$http.post('/someUrl', [body], [options]).then(successCallback, errorCallback);
vue-resource 提供了 7 种请求 API(REST 风格):
get(url, [options])
head(url, [options])
delete(url, [options])
jsonp(url, [options])
post(url, [body], [options])
put(url, [body], [options])
patch(url, [body], [options])

除了 jsonp 以外,另外 6 种的 API 名称是标准的 HTTP 方法。

options 参数说明:

请输入关键字:<input type="text" v-model="keyword" @keyup="sendJsonP(keyword)"> <li v-for="r in result">{{r}}</li> <script> window.onload = function () { new Vue({ el: '#app', data: { keyword: '', result: '' methods: { sendJsonP(keyword) { let url = 'https://www.baidu.com/sugrec?pre=1&p=3&ie=utf-8&json=1&prod=pc&from=pc_web'; this.$http.jsonp(url, { params: { wd: keyword jsonp: 'cb'//jsonp默认是callback,百度缩写成了cb,所以需要指定下 } }).then(res => { if (res.data.g) { this.result = res.data.g.map(x => x['q']); } else { this.result = []; </script> 尝试一下 »

小乙shine