Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Vue.js how can I detect if code in created() hook runs in the browser? [duplicate]

I have a Vue SSR-application and for some components, I need to know whether they run on Node during server-side rendering or whether they run on the browser.

I've set the process env in the Webpack config like

process.env.VUE_ENV === 'server' 

which works. But for various reasons, I need a detection independent of the built environment.

I'd like to check for the browser/node in the created() hook.

How would I do that?

like image 987
LongHike Avatar asked Nov 21 '18 10:11

LongHike


People also ask

How do you call a function on page load in Vue?

We can call a Vue. js method on page load by calling it in the beforeMount component hook. We can also make a method run on page load by calling it in the created hook. And we can do the same in the mounted hook.

How does Vue determine route changes?

To listen for route change events with Vue. js and Vue Router, we can watch the $route object in our component. to watch the $route in our component. We set deep to true to watch for all changes in the $route object's contents.

Should you use JSX with Vue?

The vue template is much more readable and easier to understand than jsx functions. In short, it's better to use the vue template because it's easier to implement dynamic pages with it (and other things). Also, at this point it's not a very good idea to keep sending html code through methods.

What is render function in Vuejs?

A render function returns a virtual DOM node, commonly named VNode in the Vue ecosystem, which is an interface that allows Vue to write these objects in your browser DOM. They contain all the information necessary to work with Vue.


1 Answers

I took the following line -verbatim- from the Vue.js source code ..

const inBrowser = typeof window !== 'undefined';

You can use it to verify if your code is running in the browser.

like image 161
Husam Ibrahim Avatar answered Oct 17 '22 09:10

Husam Ibrahim