Vue axios数据请求get、post方法的使用

我们常用的有get方法以及post方法

如果已安装 axios 请忽略
安装axios
npm install --save axios
安装之后
采用按需引入的方法,哪个页面需要请求数据就在哪个页面里引入一下。
import axios from 'axios'
也可全局引入
/*main.js*/

import axios from 'axios'

Vue.prototype.$axios = axios;

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

Get方法

methods:{
    
    getInfo(){
        let url = "/api/login"
        this.$axios.get(url).then((res)=>{
            console.log(res)
        }).catch(err=>{})    
    }  ,
    //方法一
    getInfo(){
        let url = "/api/login?id=123465"
        this.$axios.get(url).then((res)=>{
            console.log(res)
        }).catch(err=>{}) 
    },
    //方法二   推荐
    getInfo(){
        let url = "/api/login"
        let  params={
                id:123456
            }
        this.$axios.get(url,{params })
          .then((res)=>{
            console.log(res)
          }).catch(err=>{}) 
    },
}

Post 的用法

// 提示:该方式传递的参数是json格式,如上传不成功,需检查后台接收的方式是不是application/x-www-form-urlencoded默认格式,jquery中ajax请求的就是application/x-www-form-urlencoded,后台需要body-parser解码
        this.$axios.post('/api/post', {
          // 此参数就是写到请求体中的参数
          stuName: '盖聂',
          height: 180
        }).then((response) => {
          console.log(response);
          console.log(response.data);
        }).catch((error) => {
          console.log(error);
        });
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。