Ответ 1
Давай посмотрим, смонтированы() Думаю, это поможет
У меня есть следующий компонент 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 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
Что я делаю неправильно?
Давай посмотрим, смонтированы() Думаю, это поможет
// 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
}
}
Вы импортируете функцию извне основного экземпляра и не добавляете ее в блок методов. поэтому контекст this
не является vm.
Либо сделайте следующее:
ready() {
checkAuth.call(this)
}
или сначала добавьте метод к вашим методам (который будет корректно связывать Vue bind this
) и вызовет этот метод:
methods: {
checkAuth: checkAuth
},
ready() {
this.checkAuth()
}
Вы можете использовать mounted()
VueLifecycle Hook. Это позволит вам вызвать метод до загрузки страницы.
Это пример реализации:
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 your name?')
}
}
})
Это позволит получить значение метода подсказки, вставить его в имя переменной и вывести в DOM после загрузки страницы. Вы можете проверить пример кода здесь.
Подробнее о крюках жизненного цикла выможете прочитать здесь.
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
}
}
})
Если вам нужно запустить код после 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