run script before html is loaded vuejs

I want to test if the user has login or not, if not he will return to login page. I want the script that check if the user has login to be executed before html (or template) load. I have tried

beforeCreate()

and other things, but html still load before the script run. this is my code

if(sessionStorage.getItem("email") == undefined) location.href = "/";

edit I made this vue project using CLI so I dont have the normal index.html with head and body where i can simply add script anywhere outside vue.


#1 Answers

try

if(sessionStorage.getItem("email") == undefined) {
   location.href = "/";
} else {
   var app = new Vue({
  el: '#app',
  data: {
    message: 'Hello Vue!'
  }
})

}


#2 Answers

It isn't considered "best practice" to implement security code using JavaScript. If a user turns off JavaScript in their browser, they have effectively bypassed your security.

Instead, use server-side code to detect if the current user is logged in, and if not, send an HTML redirect to the login page instead of the normal HTML content.

Pseudo code (as you haven't specified any server-side language):

if(userLogin <> true)
    Return HtmlRedirect("YourLoginPage")
...
Return CuurrentPage

This method prevents any HTML being sent to the user if they are not authorised to see it.


#3 Answers

I agree with @Dragonlaird said mentioning that it is not a best practise to handle it from the client side. However, I think you have to try beforeMount or beforeUpdate instead of beforeCreate since you need to do the stuff before html (or template) load. According to the Vue.js documentation,

  1. beforeMount: It is called right before the mounting begins: the render function is about to be called for the first time.

But this hook is not called during server-side rendering.

  1. beforeUpdate: It is called when data changes, before the DOM is patched. This is a good place to access the existing DOM before an update, e.g. to remove manually added event listeners.

This hook is also not called during server-side rendering, because only the initial render is performed server-side.

For further informations please refer the Vue.js documentation.

https://vuejs.org/v2/api/#Options-Lifecycle-Hooks

Comments