• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

怎么用vue.js做异步请求?

vue 搞代码 4年前 (2021-12-26) 30次浏览 已收录 0个评论

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

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

请求结果:

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 =&<div style="color:transparent">来源gaodai.ma#com搞#代!码网</div>gt; 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答疑栏目,欢迎学习!

以上就是怎么用vue.js做异步请求?的详细内容,更多请关注gaodaima搞代码网其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:怎么用vue.js做异步请求?

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址