Reputation: 71
I have a Vue Component in .NET Core MVC where I do an Ajax call to get the info to use it in the Vue Component to show information. I tried it out and it was doing great, the problem is when I update the value of the Database, let's say the initial value is 200 if I update to 500, the value just disappears or doesn't update in the Vue Component, but I know that the value is being returned correctly because I've placed some console.logs to show me the output of the value.
Vue component:
<template>
<div class="framed">
<div class="column-group gutters">
<div class="all-100">
<p>Money: <strong>{{balance2}}</strong> </p>
</div>
</div>
</div>
</template>
<script>
import $ from 'jquery';
export default {
name: "credit-recharge-component",
data() {
return {
balance2: ''
}
},
created() {
this.created()
},
methods: {
created: function () {
let cobject = this;
$.ajax({
url: '/Mout/GetBalance',
type: 'GET',
contentType: 'application/json',
success: function (data) {
cobject.balance2 = data;
console.log(data)
},
error: function (error) {
console.log(JSON.stringify(error));
}
});
}
}
};
</script>
This is my razor view:
<div id="credit">
<credit-recharge-component></credit-recharge-component>
</div>
@section scripts{
<script src="@Url.Content("~/bundle/Main.js")"></script>
}
So to resume, if I change the value in the Database, the value in {{balance2}}
will not update or will disappear.
Upvotes: 0
Views: 770
Reputation: 339
I believe the problem is the "this" in success function, maybe is not the vue instance. I would try change this arrow function to regular function or to create auxiliar variable.
onCreate: function () {
var self = this;
$.ajax({
url: '/Mout/GetBalance',
type: 'GET',
contentType: 'application/json',
success: (data) => {
console.log(self.balance2);
self.balance2 = data;
console.log(data)
},
error: (error) => {
console.log(JSON.stringify(error));
}
});
}
I would log the value in self.balance2 to make sure i had the right "this".
Upvotes: 0
Reputation: 751
First, I prefer using anonymous function, then you don't have to create a variable for "this" and can directly use "this" in the function.
Can you try this code ? I think there's a problem because your two functions had the same name.
<script>
import $ from 'jquery';
export default {
name: "credit-recharge-component",
data() {
return {
balance2: ''
}
},
created() {
this.onCreate()
},
methods: {
onCreate: function () {
$.ajax({
url: '/Mout/GetBalance',
type: 'GET',
contentType: 'application/json',
success: (data) => {
this.balance2 = data;
console.log(data)
},
error: (error) => {
console.log(JSON.stringify(error));
}
});
}
}
};
</script>
Upvotes: 1