vue-resource
安装
npm install vue-resource
引入
像jquery插件要在jquery之后引入一样,vue-resource要在vue之后才引入
import VueResource from 'vue-resource';
Vue.use(VueResource);
使用
vue-resource的使用方法和jquery的ajax使用方法可以说是一毛一样的。
简直可以把resource就当作ajax来用。
get方法
this.$http.get("http://localhost/test.php").then(
function (res) {
// 处理成功的结果
console.log(res.body);
},function (res) {
// 处理失败的结果
}
);
post方法
this.$http.post("http://localhost/test.php",{name:"zhangsan"},{emulateJSON:true}).then(
function (res) {
// 处理成功的结果
console.log(res.body);
},function (res) {
// 处理失败的结果
}
);
test.php
<?php
// 指定允许其他域名访问
header('Access-Control-Allow-Origin:*');
// 响应类型
header('Access-Control-Allow-Methods:GET,POST,PUT');
header('Access-Control-Allow-Headers:x-requested-with,content-type');
var_export($_POST);
die('hello');
值得一提的是,自从 Vue 更新到 2.0 之后,官方就不再更新 vue-resource。目前来说,VueJS推荐使用axios网络请求处理方案。因为axios属于isomorphic方案,正好和VueJS2支持服务端渲染暗合。
vue执行ajax请求
js代码
var demo = new Vue({
el: '#demo',
data: {
txt: 1,
},
methods: {
ajax: function() {
var self = this;
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var json = JSON.parse(xmlhttp.responseText)
console.log(json)
console.log(self.a)
self.a = json.name;
}
}
xmlhttp.open("GET", "test.php", true);
xmlhttp.send();
}
}
})
html代码
<p>{{txt}}</p>
<button @click="ajax()">Ajax</button>
php代码
<?php
echo json_encode(array('name'=>'xunyhu'));
?>