vue http get html模板,怎么用vue.js做异步请求?

前端的数据均是通过接口请求拿到的,而Vue本身不支持ajax请求,那么该怎么解决Vue中的异步请求呢?下面我们就来看一下vue中实现异步请求的方法。

430382cbf822e14ffd5dba468d4c018b.png

一、axios实现异步请求

1.项目中安装axioxnpm install --save axios

2.在main.js中引入以供全局使用import axios from 'axios'

//可以给axios的ajax请求设置统一的主机和端口号

axios.defaults.baseURL = "http://157.122.54.189:8080/";

//将axios这个对象添加到Vue的原型对象中,在使用的时候就只需要使用this.对象名就可以了

Vue.prototype.$http = axios

3.axios之get请求

vue前端:

export default {

methods:{

getData(){

//axios-get请求

this.$http.get('/getData1')

.then(r => console.log(r))//接口调用成功返回的数据

.catch(err => console.log(err)),//接口调用失败返回的数据

}

}

mounted(){//模板或el对应的html渲染完成后再调用里面的方法

this.getData()

}

}

node后端:server.get('/getData1',function(req,res){

res.send({

'msg':'aaa'

})

})

请求结果:

725895be1e8b5493f42e0d517ffeec93.png

4.axios之post请求

Vue前端:

提交参数的两种形态:

// 1.可以直接传入字符串 name=张三&age=19

// 2.可以以对象的形式传入{name:“三”,age:19}

export default {

methods:{

getData(){

//axios-post请求传值

this.$http({

method:"post",

url:"/getData2",

headers:{

'Content-type': 'application/x-www-form-urlencoded'

},

data:{

name:'xxx'

},

transformRequest: [function (data) {//更改传值格式

let ret = ''

for (let it in data) {

ret += encodeURIComponent(it) + '=' +

encodeURIComponent(data[it]) + '&'

}

return ret.slice(0,ret.length-1)

}],

})

.then(r => console.log(r))

.catch(err => console.log(err))

}

}

mounted(){//模板或el对应的html渲染完成后再调用里面的方法

this.getData()

}

}

node后端:server.post('/getData2',function(req,res){

req.on("data",function(data){

console.log(querystring.parse(decodeURIComponent(data)));

});

res.send({

'msg':'bbb'

})

})

二、vue-resource实现异步请求(和axios步骤基本相同)

1.项目中安装vue-resourcenpm install --save vue-resource

2.在main.js中引入以供全局使用import vueResource from 'vue-resource'

Vue.use(vueResource)//这儿有所不同

3.vue-resource之get请求this.$http.get('/getData1')

.then(r => console.log(r))//接口调用成功返回的数据

.catch(err => console.log(err)),//接口调用失败返回的数据

4.vue-resource之post请求this.$http.post('/getData2',{name:"bbb"})

.then(r => console.log(r))//接口调用成功返回的数据

.catch(err => console.log(err)),//接口调用失败返回的数据

本文来自Vue.js答疑栏目,欢迎学习!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值