我得到了下一个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
我做错了什么?
7条答案
按热度按时间bvjxkvbb1#
mounted()
我觉得有帮助https://v2.vuejs.org/v2/api/#mounted
js5cn81o2#
kiz8lqtg3#
如果需要在100%加载image和files后运行代码,请在
mounted()
中测试:更多信息:Event onreadystatechange - MDN
68de4m5k4#
您可以使用**
mounted()
**Vue生命周期挂钩。这将允许您在页面加载之前调用方法。这是一个实现示例:
超文本标记语言:
联属萨摩亚
这将获取**
prompt method
的值,插入到变量name
中,页面加载后输出到DOM
中,可以查看代码示例here。您可以在此处阅读更多关于生命周期挂钩**的信息。
tmb3ates5#
你从主示例的外部导入函数,而不是将它添加到方法块中,所以
this
的上下文是 * 不是 * vm。要么这样做:
或者先将该方法添加到你的方法中(这将使Vue正确地为你绑定
this
),然后调用这个方法:fsi0uk1n6#
Vue
watch()
生命周期钩子,可以使用联系我们
联系我们
tjrkku2a7#
你可以像这样在load上调用一个函数: