【问题标题】:TypeError: app.$axios is undefined in Vue.js 3TypeError: app.$axios 在 Vue.js 3 中未定义
【发布时间】:2021-05-22 15:37:24
【问题描述】:

我有一个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 运行它时,我收到一条错误消息:

未捕获的类型错误:app.$axios 未定义

为什么app.$axios 不存在?

【问题讨论】:

    标签: javascript vue.js axios vuejs3


    【解决方案1】:

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

    docs

    globalProperties

    添加一个可以在应用程序内的任何组件实例中访问的全局属性。当存在冲突的键时,组件的属性将优先。

    所以你可以在应用程序或组件实例中使用它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';
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-18
      • 2020-09-20
      • 2021-08-30
      • 2019-06-13
      • 1970-01-01
      • 2022-08-10
      • 2020-09-06
      • 2022-09-23
      相关资源
      最近更新 更多