0

So in my main.js file, I have the following set:

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

and in one of my components: dashboard.vue

I am using the beforeRouteEnter

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

However, I get a TypeError: Cannot read property 'api_url' of undefined

On another component where I'm not using the beforeRouteEnter, I am able to access this.api_url without using an import statement at the component level.

Any thoughts or suggestions?

1 Answer 1

1

In general, to avoid conflict, you need to define and use it with a dollar sign $:

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

and

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

UPDATE

As explained here, inside beforeRouteEnter you don't have access to this because the component isn't created yet.

  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!   },

To access this, you can pass a callback inside next() function, like this:

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

Update II

as for Sphinx comment down here,

you can import Vue in your dashboard.vue, then directly access Vue.prototype.$api_url

and that will work too, before the component actually mounts.

Hope this helps!

Sign up to request clarification or add additional context in comments.

14 Comments

facing: TypeError: Cannot read property '$api_url' of undefined
Nice :) . Where beforeRouteEnter is placed in your component? Inside a method?
this is not yet defined in beforeRouteEnter. use vm.$api_url to access it
vm isnt defined either, before next(vm =>{
import Vue in your dashboard.vue, then directly access Vue.prototype.$api_url
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.