Reputation: 2047
I'm trying to use a computed method total
this calculate the number of word and multiply to a price
.
The price
is obtained with a method accessing an API.
But the computed method don't use the updated data price
. Its returning empty.
var app = new Vue({
el: '#app',
data: {
text: '',
qualidade: '',
selected: '',
options: [],
lang1: '',
lang2: '',
ola: '',
price: ''
},
beforeCreate: function() {
axios.get('/languages.json')
.then((response) => {
this.options = response.data
})
},
computed: {
total: function() {
return (this.words * this.preco).toLocaleString('de-DE')
},
words: function() {
if(this.text.length == 0) {
return 0
} else {
this.words = this.text.split(' ').length
console.log(this.words)
return this.text.split(' ').length
}
}
},
methods: {
price: function () {
axios.post('/service/price', {
lang_origem: this.lang1,
lang_dest: this.lang2
})
.then(function (response) {
this.preco = response.data.price
console.log(this.price)
})
.catch(function (error) {
console.log(error);
});
}
}
})
Upvotes: 0
Views: 54
Reputation: 20845
Problems I am able to see in your codes,
price
, they would clash.preco
is not reactive. If it's not reactive, changing its value will not update the computed values which depends on it. You should add preco
to data to make it reactive.this
in this.preco = ...
would not be referring to the Vue instanceUpvotes: 1
Reputation: 491
this.preco
will be empty as long the server call ( axios.post('/service/price' ...)
is not finished you need to rewrite this to a method that updates the this.total
Something like this:
{
methods: {
calcTotal: function () {
this.price()
.then(() => {
this.total = (this.words * this.preco).toLocaleString('de-DE')
})
},
price: function () {
//return so that we can wait on this to be finished
return axios.post('/service/price', {
lang_origem: this.lang1,
lang_dest: this.lang2
})
.then(function (response) {
this.preco = response.data.price
console.log(this.price)
})
.catch(function (error) {
console.log(error);
});
}
}
}
Upvotes: 0