vue.js:页面加载后如何调用函数?

aiazj4mn  于 2023-03-31  发布在  Vue.js
关注(0)|答案(7)|浏览(220)

我得到了下一个Vue组件。Login作为调用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
我做错了什么?

bvjxkvbb

bvjxkvbb1#

mounted()我觉得有帮助
https://v2.vuejs.org/v2/api/#mounted

js5cn81o

js5cn81o2#

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

kiz8lqtg3#

如果需要在100%加载imagefiles后运行代码,请在mounted()中测试:

mounted() {

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

}

更多信息:Event onreadystatechange - MDN

68de4m5k

68de4m5k4#

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

超文本标记语言:

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

联属萨摩亚

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 method的值,插入到变量name中,页面加载后输出到DOM中,可以查看代码示例here
您可以在此处阅读更多关于
生命周期挂钩**的信息。

tmb3ates

tmb3ates5#

你从主示例的外部导入函数,而不是将它添加到方法块中,所以this的上下文是 * 不是 * vm。
要么这样做:

ready() {
  checkAuth.call(this)
}

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

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

fsi0uk1n6#

Vue watch()生命周期钩子,可以使用
联系我们

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

联系我们

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

tjrkku2a7#

你可以像这样在load上调用一个函数:

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

相关问题