微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐