从组件级别访问vue.prototype

时间:2020-07-10 15:57:29

标签: vue.js vuejs2

因此在我的main.js文件中,我进行了以下设置:

Vue.prototype.api_url = 'http://localhost'

以及我的组件之一:dashboard.vue

我正在使用beforeRouteEnter

export default {
data() {
    return {
    }
},
beforeRouteEnter (to, from, next) {
    axios.post(this.api_url + '/dashboard')
}}}

但是,我得到一个TypeError: Cannot read property 'api_url' of undefined

在不使用beforeRouteEnter的另一个组件上,无需在组件级别使用import语句就可以访问this.api_url。

有什么想法或建议吗?

1 个答案:

答案 0 :(得分:1)

通常,为避免冲突,您需要使用$定义和使用它:

Vue.prototype.$api_url = 'http://localhost'

axios.post(this.$api_url + '/dashboard')

更新

here所述,在beforeRouteEnter内,您尚未访问此权限,因为尚未创建组件。

  beforeRouteEnter (to, from, next) {
    // called before the route that renders this component is confirmed.
    // does NOT have access to `this` component instance,
    // because it has not been created yet when this guard is called!   },

要访问此代码,可以在next()函数内部传递一个回调,如下所示:

    beforeRouteEnter (to, from, next) {
        next(that => {
            console.log(that.$api_url );
        })
    }

更新II

关于狮身人面像在这里的评论,

您可以在仪表板中导入Vue。vue,然后直接访问 Vue.prototype。$ api_url

,并且在实际安装组件之前也可以。

希望这会有所帮助!