How to access the window object in Vue.js?

Sometimes, we want to access the window object in Vue.js.

In this article, we’ll look at how to access the window object in Vue.js.

How to access the window object in Vue.js?

To access the window object in Vue.js, we can add window properties as global properties.

For instance, in Vue 2, we write

import Vue from 'vue';

Vue.prototype.$authUser = window.authUser;

to add the window.authUser value into the Vue prototype.

Then we can access routes in our component with

this.$authUser 

In Vue 3, we add the same property into app.config.globalProperties.

We write

app.config.globalProperties.$authUser = window.authUser;

Then we can access routes in our component with

this.$authUser 

Conclusion

To access the window object in Vue.js, we can add window properties as global properties.