首頁  >  文章  >  web前端  >  怎麼用vue.js做非同步請求

怎麼用vue.js做非同步請求

藏色散人
藏色散人原創
2020-12-14 11:03:315127瀏覽

用vue.js做非同步請求的方法:先在專案中安裝axiox;然後在main.js中引入axiox,以供全域使用;接著進行axios get請求;最後實作axios post請求即可。

怎麼用vue.js做非同步請求

本教學操作環境:windows7系統、vue2.0版本、thinkpad t480電腦。

推薦:《vue教學

用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(&#39;/getData1&#39;)
         .then(r => console.log(r))//接口调用成功返回的数据
         .catch(err => console.log(err)),//接口调用失败返回的数据
    }
  }
  mounted(){//模板或el对应的html渲染完成后再调用里面的方法
 this.getData()
  }
}
</script>
<style scoped>
</style>
node后端:
server.get(&#39;/getData1&#39;,function(req,res){
  res.send({
    &#39;msg&#39;:&#39;aaa&#39;
  })
})

請求結果:

怎麼用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:{
              &#39;Content-type&#39;: &#39;application/x-www-form-urlencoded&#39;
          },
          data:{
              name:&#39;xxx&#39;
          },
          transformRequest: [function (data) {//更改传值格式
              let ret = &#39;&#39;
              for (let it in data) {
                ret += encodeURIComponent(it) + &#39;=&#39; + 
                encodeURIComponent(data[it]) + &#39;&&#39;
              }
              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(&#39;/getData2&#39;,function(req,res){
  req.on("data",function(data){
      console.log(querystring.parse(decodeURIComponent(data)));
  });
  res.send({
    &#39;msg&#39;:&#39;bbb&#39;
  })
})

二、vue-resource實作非同步請求(和axios步驟基本上相同)

1.專案中安裝vue -resource

npm install --save vue-resource

2.在main.js中引入以供全域使用

import vueResource from &#39;vue-resource&#39;
Vue.use(vueResource)//这儿有所不同

3.vue-resource之get請求

this.$http.get(&#39;/getData1&#39;)
    .then(r => console.log(r))//接口调用成功返回的数据
    .catch(err => console.log(err)),//接口调用失败返回的数据

4.vue-resource之post請求

this.$http.post(&#39;/getData2&#39;,{name:"bbb"})
    .then(r => console.log(r))//接口调用成功返回的数据
    .catch(err => console.log(err)),//接口调用失败返回的数据

以上是怎麼用vue.js做非同步請求的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn