Vue 使用 axios 请求的两种方式

axios 是一个基于 promise 的 HTTP 库,类似于 jQuery 的 Ajax,用于 HTTP 请求。可以在浏览器和 node.js 中使用。

一.axios 安装:

 

使用命令:

npm install axios

 

 二 . 安装 qs:

 

使用命令:

 npm install qs

 

三.引入 axios 与 qs【全局引入】:

在 main.js 文件中引入 axios 与 qs,并绑定到 vue 的原型上。

import Vue from 'vue'
import App from './App.vue'
import router from './router'

Vue.config.productionTip = false;

// 1.引入axios
import axios from 'axios'
// 2.引入qs
import qs from 'qs'
// 3.将axios绑定到vue原型上,并命名为$axios
Vue.prototype.$axios = axios;
// 4.将qs绑定到vue原型上,并命名为$qs
Vue.prototype.$qs = qs;

new Vue({
  router,render: h => h(App),}).$mount('#app')

 axios 基础使用

一、get 请求

<template>
    <div>
        <p>{{ name }}</p>
    </div>
</template>

<script>
export default {
    name: "Home",data() {
        return {
            name: "GET请求"
        }
    },created() {

        // 1. 第一种写法
        this.$axios({
            method: 'get',url: 'http://xxx/webapi/user/info',params: {
                id: 1
            }
        }).then((res) => {
            console.log(res.data);
        })

        // 2. 使用get别名写法
        this.$axios.get('http://xxx/webapi/user/info',{
            params: {
                id: 1
            }
        }).then((res) => {
            console.log(res.data);
        })

    }
}
</script>

二、post 请求

<template>
    <div>
        <p>{{ name }}</p>
    </div>
</template>

<script>
export default {
    name: "Home",data() {
        return {
            name: "POST请求"
        }
    },created() {

        // 1. 第一种写法
        this.$axios({
            method: 'post',data: {
                id: 1
            }
        }).then((res) => {
            console.log(res.data);
        })

        // 2. 使用post别名写法
        this.$axios.post('http://xxx/webapi/user/info',{
            id: 1
        }).then((res) => {
            console.log(res.data);
        })

    }
}
</script>

原创作者:吴小糖

创作时间:2023.6.21

相关文章

这篇文章我们将通过debug源码的方式来带你搞清楚defineAsync...
欧阳老老实实的更新自己的高质量vue源码文章,还被某2.6k st...
前言 在Vue3.5版本中响应式 Props 解构终于正式转正了,这个...
组合式 (Composition) API 的一大特点是“非常灵活”,但也因...
相信你最近应该看到了不少介绍Vue Vine的文章,这篇文章我们...
前言 在欧阳的上一篇 这应该是全网最详细的Vue3.5版本解读文...