[vue.js] Vue.JS: How to call function after page loaded?

I have got next Vue component. Login as calling Login function. checkAuth -- is calling checking Authorization status between page refresh.

But how I can call checkAuth without pushing on button?

var GuestMenu = Vue.extend({
    props: ['username', 'password'],
    template: `
        <div id="auth">
            <form class="form-inline pull-right">
                <div class="form-group">
                    <label class="sr-only" for="UserName">User name</label>
                  <input type="username" v-model="username" class="form-control" id="UserName" placeholder="username">
                </div>
                <div class="form-group">
                  <label class="sr-only" for="Password">Password</label>
                  <input type="password" v-model="password" class="form-control" id="Password" placeholder="Password">
                </div>
              <button type="submit" class="btn btn-default" v-on:click.prevent="sendLoginInfo()">LOGIN</button>
              <button type="submit" class="btn btn-default" v-on:click.prevent="checkAuth()">CheckAuth</button>
            </form>
        </div>`,

    methods: { 
        //hash key-value
        sendLoginInfo: sendLoginInfo, // key (anyname) | value -> calling function name (from separate file) 
        
        //calling without brackets because we do need return from function, we need just function
        checkAuth: checkAuth // restore authorization after refresh page if user already have session!
    }
});

I tried to call it's from App:

App = new Vue({ // App -- is need for overwrite global var. Global var need declarated abobe all function, because some it's function is calling from outside
        el: '#app',
        data: {
            topMenuView: "guestmenu",
            contentView: "guestcontent",
            username: "",
            password: "",

        },
        ready: function() {
            checkAuth(); // Here

        }
    }
)

But it's look like it's calling when not all components are loaded,

function checkAuth() {
    // we should NOT send any data like: loginData because after refreshing page
    // all filds are empty and we need to ask server if he have authorize session

    console.log("Checking if user already have active session");

    this.$http.post('http://127.0.0.1:8080/checkAuthorization').then(function(response) {
            console.log("server response: ", response.data)
        }
    }
    // ...
}

Here I am getting error:

authorization.js:69 Uncaught TypeError: Cannot read property 'post' of undefined

I tried to do:

{
// ...
    methods: { //hash key-value
      sendLoginInfo : sendLoginInfo, // key (anyname) | value -> calling function name (from separate file) 
      //calling without brackets because we do need return from function, we need just function

    },
    ready()
    {
      checkAuth()
    }
// ...
}

But again got error: Uncaught TypeError: Cannot read property 'post' of undefined

What I am doing wrong?

This question is related to vue.js

The answer is


Let see mounted() I think it is help

https://vuejs.org/v2/api/#mounted


You can use the mounted() Vue Lifecycle Hook. This will allow you to call a method before the page loads.

This is an implementation example:

HTML:

<div id="app">
  <h1>Welcome our site {{ name }}</h1>
</div>

JS:

var app = new Vue ({
    el: '#app',
    data: {
        name: ''
    },
    mounted: function() {
        this.askName() // Calls the method before page loads
    },
    methods: {
        // Declares the method
        askName: function(){
            this.name = prompt(`What's your name?`)
        }
    }
})

This will get the prompt method's value, insert it in the variable name and output in the DOM after the page loads. You can check the code sample here.

You can read more about Lifecycle Hooks here.


// vue js provides us `mounted()`. this means `onload` in javascript.

mounted () {
  // we can implement any method here like
   sampleFun () {
      // this is the sample method you can implement whatever you want
   }
}

Vue watch() life-cycle hook, can be used

html

<div id="demo">{{ fullName }}</div>

js

var vm = new Vue({
  el: '#demo',
  data: {
    firstName: 'Foo',
    lastName: 'Bar',
    fullName: 'Foo Bar'
  },
  watch: {
    firstName: function (val) {
      this.fullName = val + ' ' + this.lastName
    },
    lastName: function (val) {
      this.fullName = this.firstName + ' ' + val
    }
  }
})

You import the function from outside the main instance, and don't add it to the methods block. so the context of this is not the vm.

Either do this:

ready() {
  checkAuth.call(this)
}

or add the method to your methods first (which will make Vue bind this correctly for you) and call this method:

methods: {
  checkAuth: checkAuth
},
ready() {
  this.checkAuth()
}

If you need run code after 100% loaded with image and files, test this in mounted():

document.onreadystatechange = () => {
  if (document.readyState == "complete") {
    console.log('Page completed with image and files!')
    // fetch to next page or some code
  }
}

More info: MDN Api onreadystatechange