欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

vue axios数据请求get、post方法及实例详解

程序员文章站 2023-12-10 08:52:34
我们常用的有get方法以及post方法,下面简单的介绍一下这两种请求方法 vue中使用axios方法我们先安装axios这个方法 npm install --save...

我们常用的有get方法以及post方法,下面简单的介绍一下这两种请求方法

vue中使用axios方法我们先安装axios这个方法

npm install --save axios

安装之后采用按需引入的方法,哪个页面需要请求数据就在哪个页面里引入一下。

import axios from 'axios'

引入之后我们就可以进行数据请求了,在methods中创建一个方法

 methods:{
   getinfo(){
     let url = "url"
     axios.get(url).then((res)=>{
       console.log(res)
     })   
   } 
 }

然后我们在mounted这个生命周期中进行调用

 mounted(){
   this.getinfo() 
 }

这样就可以在控制台中查看数据,以上是一个简单的get方法数据请求,下面继续介绍一下post方法的使用,其实post和get的使用没有什么区别只是再加上一个参数就可以了,看一下我们的代码

 methods:{
   postinfo(){
     let url = "url"
     let params=new urlsearchparams();//这个方法在axios的官网中有介绍,除了这个方法还有qs这个方法
     params.append("key",index) 
     params.append("key",index)
     axios.post(url,params).then((res)=>{
       console.log(res)
     })
   }  
 }

同样在mounted这个生命周期中进行调用

 mounted(){
   this.postinfo()
 }

补充:下面看下axios 数据请求

项目地址:

axios是一个基于promise,同时支持浏览器端和node.js的http库,常用于ajax请求。

vue.js 不像jquery 或 angularjs,本身并没有带ajax方法,因此需要借助插件或第三方http库。

get和post请求

 axios.get("./package.json",{
     params:{
      userid:"999"
     },
     headers:{
      token:"jack"
     }
    }).then(res=>{
     this.msg = res.data;
    }).catch(function (error) {
     console.log("error init."+error)
    });

post:

<code class="language-javascript"> axios.post("./package.json",{ 
     userid:"888" 
    },{ 
     headers:{ 
      token:"tom" 
     } 
    }).then(res=>{ 
     this.msg =res.data 
    }).catch(err=>{ 
      console.log(err) 
    })</code> 

基于promise 可以执行多个并发请求:1

 function getuseraccount(){
    return axios.get('/user/123')
   }
   function getuserpermissions(){
    return axios.get('/user/12345/premissions')
   }
   axios.all([getuseraccount(),getuserpermissions()])
   .then(axios.spread(function(acct,perms){
     //请求都完时
   }))

也可通过写入配置的形式发起请求:

  axios({
  method:'post',
  url:'/user/123',
  data:{
   firstname:'fred',
   lastname:'flintstone'
  }
  }).then(function(res){
  console.log(res)
  })

在业务中经常将其封装为实例形式调用,便于通用配置:

// util.js
const instance = axios.create({
 baseurl:"http://jsonplaceholder.typicode.com/",
 timeout:1000,
 headers:{"content-type":"application/x-www-form-urlencoded"}
})
export default instance;

在mounted中调用:

ajax({
    method:'post',
    url:'/package.json',
    data:{
    firstname:'fred',
    lastname:'flintone'
    }
   }).then(res=>{
     console.log(res.data)
     this.msg = res.data
   })

强求拦截可用于loading..

axios.interceptors.request.use(config=>{
    console.log("require init");
    return config
   })
    axios.interceptors.response.use(response=>{
    console.log("response init");
    return response
   })

总结

以上所述是小编给大家介绍的vue axios数据请求get、post方法及实例详解,希望对大家有所帮助