赞
踩
方法是在main.js中写入
- import { createApp } from 'vue'
- import App from './App.vue'
- import axios from 'axios'
- const app = createApp(App)
- app.prototype.$http= axios
经过踩坑,发现vue3.0取消了Vue.prototype,官方文档推荐使用globalProperties
于是main.js改写成
- import { createApp } from 'vue'
- import App from './App.vue'
- import axios from 'axios'
- const app = createApp(App)
- app.config.globalProperties.$http = axios
然后在组件中引用
- this.$http.get('api/getNewsList')
- .then((response)=>{
- console.log(response)
- })
继续踩坑
vue3.0中是没有this的。使用getCurrentInstance来获取上下文
const { proxy } = getCurrentInstance() 这里的proxy相当于this
- const { proxy } = getCurrentInstance()
- proxy.$http.get('api/getNewsList')
- .then((response)=>{
- console.log(response)
- })
首先在主入口文件main.js中引用:
- import { createApp } from 'vue'
- import App from './App.vue'
- import axios from 'axios'
- import VueAxios from 'vue-axios'
- const app = createApp(App)
- app.use(VueAxios,axios);
然后在组件中引用,注意vue3.x没有this
- axios.get('api/getNewsList')
- .then((response)=>{
- console.log(response)
- })
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。