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',
            url: 'http://xxx/webapi/user/info',
            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

猜你喜欢

转载自blog.csdn.net/xiaowude_boke/article/details/131323518
今日推荐