TypeError: app.$axios is undefined in Vue.js 3

TypeError: app.$axios is undefined in Vue.js 3

我有一个 main.js 文件,它创建了一个 app 并向其中添加了各种内容,例如 routerstoreaxios

这就是我在全局添加 axios 所做的:

import {createSSRApp, createApp, h} from 'vue';
import axios from 'axios'    

 const rootComponent = {
        render: () => h(App),
        components: { App }
    }

const app = createApp(rootComponent);
app.config.globalProperties.$axios=axios;

if (process.env.NODE_ENV === 'development') {
        app.$axios.defaults.baseURL = 'http://localhost:8080'; // This throws an error
}

当我在浏览器中使用 webpack-dev-server 运行 时,我收到一条错误消息:

Uncaught TypeError: app.$axios is undefined

为什么 app.$axios 不存在?

因为全局 属性 在实例而不是原型上可用。

docs

globalProperties

Adds a global property that can be accessed in any component instance inside the application. The component’s property will take priority when there are conflicting keys.

因此您可以在 this

的应用程序或组件实例中使用它
this.$axios.defaults.baseURL = 'http://localhost:8080';

或者如果您在应用程序实例之外使用它,您可以按照您定义的方式访问它

// in the same file, since you have the axios object already
axios.defaults.baseURL = 'http://localhost:8080'; 

// or from somewhere else
app.config.globalProperties.$axios.defaults.baseURL = 'http://localhost:8080';