Home > Article > Web Front-end > How to use vue.js to make asynchronous requests
How to use vue.js to make asynchronous requests: first install axiox in the project; then introduce axiox in main.js for global use; then make an axios get request; and finally implement axios post request. .
The operating environment of this tutorial: windows7 system, vue2.0 version, thinkpad t480 computer.
Recommended: "vue tutorial"
Use vue.js to make asynchronous requests
1. Axios implements asynchronous requests
1. Install axiox in the project
npm install --save axios
2.Introduce it in main.js for global use
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 request
vue Front-end:
<template> <div> </div> </template> <script> 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() } } </script> <style scoped> </style> node后端: server.get('/getData1',function(req,res){ res.send({ 'msg':'aaa' }) })
Request result:
4.axios post request
Vue front-end:
Submit parameters Two forms:
// 1.可以直接传入字符串 name=张三&age=19 // 2.可以以对象的形式传入{name:“三”,age:19} <template> <div> </div> </template> <script> 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() } } </script> <style scoped> </style>
node backend:
server.post('/getData2',function(req,res){ req.on("data",function(data){ console.log(querystring.parse(decodeURIComponent(data))); }); res.send({ 'msg':'bbb' }) })
2. vue-resource implements asynchronous requests (basically the same steps as axios)
1. Install vue in the project -resource
npm install --save vue-resource
2.Introduced in main.js for global use
import vueResource from 'vue-resource' Vue.use(vueResource)//这儿有所不同
3.vue-resource get request
this.$http.get('/getData1') .then(r => console.log(r))//接口调用成功返回的数据 .catch(err => console.log(err)),//接口调用失败返回的数据
4.vue-resource post Request
this.$http.post('/getData2',{name:"bbb"}) .then(r => console.log(r))//接口调用成功返回的数据 .catch(err => console.log(err)),//接口调用失败返回的数据
The above is the detailed content of How to use vue.js to make asynchronous requests. For more information, please follow other related articles on the PHP Chinese website!