Vue.JS:如何在页面加载后调用函数?

时间:2016-05-08 09:19:54

标签: vue.js

我有下一个Vue组件。 Login调用登录功能。 checkAuth - 正在调用检查页面刷新之间的授权状态。

但是如何在不按下按钮的情况下拨打checkAuth

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!
        }

          });

我试图从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

  }

  }

  )

但是当没有加载所有组件时,看起来它正在调用

 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)
....

我在这里收到错误:

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

我试着这样做:

    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()
    }

但又出现了错误: Uncaught TypeError: Cannot read property 'post' of undefined

我做错了什么?

6 个答案:

答案 0 :(得分:10)

让我们看看mount()我认为这是帮助

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

答案 1 :(得分:6)

// 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
   }
}

答案 2 :(得分:3)

从主实例外部导入函数,不要将其添加到方法块。所以this的上下文 vm。

要么这样做:

ready() {
  checkAuth.call(this)
}

或首先将方法添加到您的方法中(这将使Vue正确绑定this)并调用此方法:

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

答案 3 :(得分:0)

您可以使用 mounted() Vuejs生命周期挂钩。这样,您就可以在页面加载之前调用方法。

这是一个实现示例:

HTML:

<div id="div-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?`)
        }
    }
})

这将获取提示方法的值,并将其插入变量名中,并在页面加载后在DOM中输出。

您可以了解有关生命周期挂钩here的更多信息。

答案 4 :(得分:0)

Vue watch() 生命周期挂钩,可以使用

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

答案 5 :(得分:-1)

如果在100%加载了图像文件后需要运行代码,请在mounted()中进行测试:

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

更多信息:MDN Api onreadystatechange