废话不多说,直接代码:
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')