2

I'm creating a plugin and I just wonder why I can't access it in main.js file. Here's how Auth.js looks like:

const Auth = {
    install(Vue) {

        Vue.prototype.$isGuest = function () {
            console.log('This user is a guest.');
        }

        Vue.prototype.$getAuthToken = function () {
            console.log('Auth token will be returned.');
        }

    }
}

export default Auth

This is main.js:

import Auth from '@/helper/Auth'
Vue.use(Auth)

However, when I execute console.log(this.$isGuest()), it doesn't work. It actually returns the following:

main.js?1c90:25 Uncaught TypeError: this.$isGuest is not a function

The problem is that this method works when I call it in components such as Dashboard.vue and things like that.

I have a way to avoid calling isGuest method within main.js (I can call it in Layout.vue), but I'm more curious why it doesn't work in main.js.

Maybe because Vue hasn't been initialized yet, but even if I put the console.log() line at the end of the file, still doesn't work.

Thanks, N.

2
  • 2
    Where is the console.log in main.js? Commented Oct 27, 2017 at 1:57
  • @Bert below Vue.use(Auth) and above new Vue({.... Commented Oct 27, 2017 at 9:19

1 Answer 1

2

If you are calling this.$isGuest() outside of Vue, you will get the error you describe. That's because this is not a Vue object. What this is depends on how you are building your code, but given you are using import it's probably the module.

Also, you are adding $isGuest to the prototype of Vue. That means that the function is only going to be available on actual instances of Vue objects. That is why it is available in your components.

If you want to use it in the main script, the only place you will be able to get to it is inside the Vue object in a lifecycle handler, method, or computed. For example:

new Vue({
  mounted(){
    console.log(this.$isGuest()) // this should work
  }
})
Sign up to request clarification or add additional context in comments.

1 Comment

how do you construct a new Vue? Builder tells me there's no constructor signature.

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.