48

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?

7 Answers 7

29

Let see mounted() I think it is help

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

1
  • 1
    This helps but I'm unsure where to add the Mounted function within my code - I'm using SFC format with app.vue etc.
    – quilkin
    Commented Jan 1, 2023 at 9:28
22
// 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
   }
}
20

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

mounted() {

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

}

More info: Event onreadystatechange - MDN

1
  • 1
    Thank you for this tip! This was exactly what I was looking for along with mounted(). Commented Dec 8, 2020 at 0:27
9

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.

7

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()
}
2
  • 3
    How can the same be done in vue.js 2. I have tried the second option using mounted but it does not work. Commented Nov 18, 2016 at 12:18
  • 2
    Well, it should work with mounted(), so your problem is likely to be something else. What that is I can'T say without any code. You should open another topic maybe.
    – Linus Borg
    Commented Nov 18, 2016 at 14:23
1

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
    }
  }
})
0
1

You can call a function on load like this:

methods:{
     checkAuth: function() {your logic here}
 },
 mounted(){
    this.checkAuth()
 },

Not the answer you're looking for? Browse other questions tagged or ask your own question.