Vue-axios挂载到Vue的原型,配置请求根路径

废话不多说,直接代码:
App.vue

<template>
	<div class="app-container">
		<h1>App 根组件</h1>
		<hr />
	
		<div class="box">
			<!-- 渲染 Left 组件和 Right 组件 -->
			<Left></Left>
			<Right></Right>
		</div>
	</div>
</template>

<script>
	import Left from '@/components/Left.vue'
	import Right from '@/components/Right.vue'
	
	export default {
		components:{
			Left,
			Right
		}
	}
</script>

<style lang="less" scoped>
	.app-container {
		padding: 1px 20px 20px;
		background-color: #efefef;
	}

	.box {
		display: flex;
	}
</style>

Left.vue

<template>
  <div class="left-container">
    <h3>Left 组件</h3>
	<button @click="getInfo">发起get请求</button>
  </div>
</template>

<script>
	// import axios from 'axios'
export default {
	methods:{
	   	async getInfo(){
		   // const {data:res} = await this.axios.get('http://www.liulongbin.top:3006/api/get')
		  const {data:res} = await this.$http.get('/api/get')
		   console.log(res)
		}
	}
	
}
</script>

<style lang="less">
.left-container {
  padding: 0 20px 20px;
  background-color: orange;
  min-height: 250px;
  flex: 1;
}
</style>

Right.vue

<template>
  <div class="right-container">
    <h3>Right 组件</h3>
	<button @click="postInfo">发起post请求</button>
	
  </div>
</template>

<script>
	// import axios from 'axios'
export default {
	methods:{
		async postInfo(){
			//this实例,通过组件的实例
		 // const {data:res}=await	this.axios.post('http://www.liulongbin.top:3006/api/post',{name:'zs',age:20})
		 const {data:res}=await	this.$http.post('/api/post',{name:'zs',age:20})
		 
		 console.log(res)
		}
	}
	
}
</script>

<style lang="less">
.right-container {
  padding: 0 20px 20px;
  background-color: lightskyblue;
  min-height: 250px;
  flex: 1;
}
</style>

main.js

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

Vue.config.productionTip = false

// 挂载
// Vue.prototype.axios=axios
//$模仿vue的内置成员
Vue.prototype.$http=axios
//在每一个vue组件中发起请求,直接调用this.$http.xxx
//全局配置axios的请求路径
// axios.default.baseURL='请求根路径'
// 今后,在每个 .vue 组件中要发起请求,直接调用 this.$http.xxx
// 但是,把 axios 挂载到 Vue 原型上,有一个缺点:不利于 API 接口的复用!!!
axios.defaults.baseURL='http://www.liulongbin.top:3006'

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

在这里插入图片描述

缺点:不利于 API 接口的复用!!!

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值