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

48

我有一个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 = 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

我错在哪了?

7个回答

29

这很有帮助,但我不确定在我的代码中应该在哪里添加Mounted函数 - 我正在使用SFC格式与app.vue等。 - quilkin

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
如果您需要在100%加载了图像文件后运行代码,请在mounted()中测试此功能:
mounted() {

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

}

更多信息:readystatechange事件 - MDN


1
谢谢您的提示!这正是我所寻找的,还有mounted()。 - PepperAddict
1
指向错误的文档页面,请使用正确的链接:https://developer.mozilla.org/zh-CN/docs/Web/API/Document/readystatechange_event - pyrsmk
1
@pyrsmk 谢谢!链接已修复 =) - Adriano Resende

9
你可以使用 mounted() Vue 生命周期钩子。这将允许你在页面加载前调用一个方法。
以下是实现示例:

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

这将获取“prompt方法”的值,将其插入到变量“name”中,并在页面加载后输出到DOM中。您可以在此处查看代码示例。
您可以在此处了解有关生命周期钩子的更多信息。

7

您需要从主实例外部导入函数,并将其添加到方法块中。因此,this 的上下文不是虚拟机。

要解决这个问题,可以采取以下方式:

ready() {
  checkAuth.call(this)
}

或者先将该方法添加到您的methods中(这将使Vue为您正确绑定this),然后调用此方法:

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

3
如何在Vue.js 2中完成相同的操作?我已经尝试使用mounted这个第二个选项,但它不起作用。 - Phillis Peters
2
好的,它应该可以使用 mounted(),所以你的问题很可能是别的地方出了问题。如果没有代码,我无法判断问题具体出在哪里。你可以考虑开一个新话题来讨论。 - Linus Borg

1
您可以像这样在加载时调用函数:
methods:{
     checkAuth: function() {your logic here}
 },
 mounted(){
    this.checkAuth()
 },

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接