I've got a login page and in my template I have a <p v-show="loading">Loading...</p>
Assuming the post request doesn't have an error and is slow, then I'd like to change the loading property to true as the request is processing. How can I do that in the script below?
*Edit* Added the template code
<template>
<div id="backend-view">
<form @submit.prevent="submit">
<p v-show="loading">Loading...</p>
<h3>Login Here</h3>
<label for="email">Email</label>
<input type="text" id="email" v-model="fields.email" />
<span v-if="errors && errors.email" >{{
errors.email[0]
}}</span>
<label for="password">Password</label>
<input type="password" id="password" v-model="fields.password" />
<span v-if="errors && errors.password" >{{
errors.password[0]
}}</span>
<button type="submit">Log In</button>
</form>
</div>
</template>
<script>
export default {
data() {
return {
fields: {},
errors: {},
loading: false
};
},
methods: {
submit() {
axios
.post("/api/login", this.fields)
.then((res) => {
if (res.status == 201) {
this.$router.push("/dashboard");
}
})
.catch((error) => {
if (error.response.status == 422) {
this.errors = error.response.data.errors;
}
});
},
},
};
</script>
CodePudding user response:
You can set a timer before calling the api which then toggles and the loading goes away.
<script>
export default {
data() {
return {
fields: {},
errors: {},
loading: false
};
},
methods: {
submit() {
this.loading = true
setTimeout(function(){
this.loading = false
}, 2000);
axios
.post("/api/login", this.fields)
.then((res) => {
if (res.status == 201) {
this.$router.push("/dashboard");
}
})
.catch((error) => {
if (error.response.status == 422) {
this.errors = error.response.data.errors;
}
});
},
},
};
</script>
CodePudding user response:
like this:
<script>
export default {
data() {
return {
fields: {},
errors: {},
loading: false
};
},
methods: {
submit() {
loading = true
axios
.post("/api/login", this.fields)
.then((res) => {
loading = false
if (res.status == 201) {
this.$router.push("/dashboard");
}
})
.catch((error) => {
if (error.response.status == 422) {
this.errors = error.response.data.errors;
}
});
},
},
};