0
点赞
收藏
分享

微信扫一扫

Vue中的 axios配置及使用

回望这一段人生 2022-05-02 阅读 125
vue.js

单组件配置(components-->.vue)

import axios from ’axios‘ 

全局配置 (main.js)

import Vue from 'vue'
import App from './App.vue'
import axios from 'axios'
Vue.config.productionTip = false

//全局配置axios的请求根路径
axios.defaults.baseURL = '请求根路径'

axios.defaults.baseURL = 'http://www.liulongbin.top:3006/'
/*
全局配置axios——把 axios挂载到Vue.prototype 上:
优点:供每个.vue组件的实例直接使用
缺点:无法实现 API接口 的复用!!!
*/

// Vue.prototype.axios = axios
// 或 用 $http 装逼
Vue.prototype.$http = axios

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

练习

App.vue

<template>
<div class="container">
<left class="left"></left>
<right class="right"></right>
</div>
</template>

<script>
import Left from "@/Components/Left";
import Right from "@/Components/Right";
export default {
components: {
Left,
Right,
},
};
</script>

<style lang="scss" scoped>
.container {
display: flex;
}
</style>

Left.vue

<template>
<div class="left">
<h1>Left.vue</h1>
<button @click="getInfo">发送get请求</button>
</div>
</template>

<script>
export default {
methods: {
async getInfo() {
const { data: res } = await this.$http.get("api/get");
/*
const { data: res } = await this.$http.get(
"http://www.liulongbin.top:3006/api/get"
);
*/

/*
const { data: res } = await this.axios.get(
"http://www.liulongbin.top:3006/api/get"
);
*/

// const a = await axios.get("https://www.escook.cn/api/cart");
console.log(res);
},
},
};
</script>

<style lang="scss" scoped>
.left {
background-color: pink;
min-height: 200px;
flex: 1;
}
</style>

Right.vue

<template>
<div class="right">
<h1>Right.vue</h1>
<button @click="postInfo">发送post请求</button>
</div>
</template>

<script>
export default {
methods: {
async postInfo() {
const { data } = await this.$http.post("api/post", {
name: "zs",
age: 20,
});
/*
const { data } = await this.$http.post("http://www.liulongbin.top:3006/api/post", {
name: "zs",
age: 20,
});
*/

// const { data } = await this.axios.post("http://www.liulongbin.top:3006/api/post", {
// name: "zs",
// age: 20,
// });
console.log(data);
},
},
};
</script>

<style lang="scss">
.right {
background-color: yellow;
height: 200px;
flex: 1;
}
</style>

效果: 

 

举报

相关推荐

0 条评论