温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

用vue.js做异步请求的方法

发布时间:2020-12-14 11:58:32 来源:亿速云 阅读:916 作者:小新 栏目:编程语言

这篇文章主要介绍了用vue.js做异步请求的方法,具有一定借鉴价值,需要的朋友可以参考下。希望大家阅读完这篇文章后大有收获。下面让小编带着大家一起了解一下。

用vue.js做异步请求的方法:首先在项目中安装axiox;然后在main.js中引入axiox,以供全局使用;接着进行axios get请求;最后实现axios post请求即可。

用vue.js做异步请求

一、axios实现异步请求

1.项目中安装axiox

npm 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前端:

<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'
  })
})

请求结果:

用vue.js做异步请求的方法

4.axios之post请求

Vue前端:

提交参数的两种形态:

// 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后端:

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-resource

npm 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做异步请求的方法内容对大家有帮助,同时也希望大家多多支持亿速云,关注亿速云行业资讯频道,遇到问题就找亿速云,详细的解决方法等着你来学习!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI