axios的挂载

axios的挂载

请求示例

如下,每一次都要导入axios,每一个组件都相当于vue的实例。

 

<template>
 <div class="left-container">
   <h3>left</h3>
   <button @click="getInfo">GET</button>
 </div>
</template>

<script>
import axios from 'axios'
export default {
 name: 'leftContainer',
 methods: {
   async getInfo () {
     const { data: res } = await axios.get('https://ajax-base-api-t.itheima.net/api/get')
     console.info(res)
  }
}
}
</script>
<template>
 <div class="right-container">
   <h3>right</h3>
   <button @click="postInfo">POST</button>
 </div>
</template>
<script>
import axios from 'axios'
export default {
 name: 'rightContainer',
 methods: {
   async postInfo () {
     const { data: res } = await axios.post('https://ajax-base-api-t.itheima.net/api/post', { name: 'zs', age: 20 })
     console.info(res)
  }
}
}
</script>

挂载

直接将axios挂载到Vue原型上并配置请求根路径。

/* eslint-disable */
import Vue from 'vue'
import App from './App.vue'
import axios from 'axios' //项目只用导入一次

Vue.config.productionTip = false

//全局配置axios的请求根路径。
axios.defaults.baseURL = ' https://ajax-base-api-t.itheima.net' //请求根路径。

//在vue原型上挂载一个共享成员:把axios挂载到Vue.prototype上,供每个.vue组件的实例直接使用。
//Vue.prototype.axios = axios两种写法都可以,仅是名字不同。
Vue.prototype.$http = axios //$前缀标识这是Vue实例的一个特殊属性。

//组件中 const { data: res } = await this.$http.get('/api/get')

//今后在每个.vue组件中发起请求,直接调用this.$http.xxx
//但是,把axios挂载到vue原型上,缺点是不利于api的调用

new Vue({
 render: h => h(App)
}).$mount('#app')
//组件的使用
methods: {
async getInfo () {
const { data: res } = await this.$http.get('/api/get')
   console.info(res)
}
}

 

缺点

无法实现api接口的复用。

posted @   yxxcl  阅读(17)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
点击右上角即可分享
微信分享提示