Reputation: 573
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.
Upvotes: 2
Views: 2683
Reputation: 82469
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
}
})
Upvotes: 2