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

相关文章

创建vite项目
Vue-router 路由安装以及使用_vue项目安装router
vue中的 axios请求_$axios请求
当你单独把这个deep放到style标签中,就会生效了:而且不能使...
Vue-resource是Vue高度集成的第三方包,能很方便的放松请求。...
理想的是页面创建时就向后台获取数据,然后将数据渲染在页面...