Reputation: 4268
I have a following component in which I have a method which updates employee. I want to show the error message in view as soon as erroMessage variable is assigned/changed in "error" callback of ajax call.
var EmployeeEdit = Vue.extend({
template: '#employee-edit',
data: function () {
return {employee: findEmployee(this.$route.params.employee_id),errorMessage:'as'};
},
methods: {
updateEmployee: function () {
var employee = this.employee;
$.ajax({
url: "/vue/employee/update",
type: "POST",
data:{
id: employee.id,
name: employee.name,
profile: employee.profile,
age: employee.age
},
success: function (data) {
router.push('/');
},
error:function (xhr, status, error) {
console.log("message....... " + xhr.responseText);
this.errorMessage = xhr.responseText;
}
});
}
View:
<template id="employee-edit">
<section>
<header class="page-header">
<div class="row">
<div class="col-sm-4">
<h1>Edit Employee</h1>
</div>
</div>
</header>
<p >{{ errorMessage }}</p>
<form v-on:submit="updateEmployee">
<div class="form-group">
<label for="edit-name">Name</label>
<input class="form-control" id="edit-name" v-model="employee.name" required/>
</div>
<div class="form-group">
<label for="edit-description">Profile</label>
<textarea class="form-control" id="edit-description" rows="3" v-model="employee.profile"></textarea>
</div>
<div class="form-group">
<label for="edit-price">Age</label>
<input type="number" class="form-control" id="edit-price" v-model="employee.age"/>
</div>
<button type="submit" class="btn btn-primary">Save</button>
<router-link to="/" class="btn btn-default">Cancel</router-link>
</form>
</section>
</template>
Upvotes: 2
Views: 6551
Reputation: 15924
Because you lost the this
reference in error:function(){}
You can use arrow functions:
error: (xhr, status, error) => {
console.log("message....... " + xhr.responseText);
this.errorMessage = xhr.responseText;
}
or if you don't want to use ES6, you can specify the context
option in $.ajax()
$.ajax({
context: this,
...
or simply keep a this
reference
updateEmployee: function () {
var _this = this;
...
error: function (xhr, status, error) {
console.log("message....... " + xhr.responseText);
_this.errorMessage = xhr.responseText;
}
Upvotes: 4