I have two methods on my Vue instance;
const app = new Vue({
el: '#app',
data: {
id: null
},
methods: {
getId: function() {
return axios.get('url')
.then(response => response.data)
.then(id => this.id = id)
.catch(error => console.log(error))
},
foo: function() {
console.log(this.id)
}
},
mounted: function() {
this.getId()
this.foo()
}
})
The console.log()
logs null
as the value because it runs before the response getId()
has managed to set the id
value. I know this because when I use Vue developer tools, the id is the actual value I was expecting rather than null
.
How can I make sure getId()
has set the value before running this.foo()
?
You can use JavaScript promises to achieve this. The simplest way would be to use the async/await syntax ..
const app = new Vue({
el: '#app',
data: {
id: null
},
methods: {
getId: function() {
return axios.get('url')
.then(response => response.data)
.then(id => this.id = id)
.catch(error => console.log(error))
},
foo: function() {
console.log(this.id)
}
},
mounted: async function() {
await this.getId()
this.foo()
}
})
Or you can go the old-fashioned way ..
const app = new Vue({
el: '#app',
data: {
id: null
},
methods: {
getId: function() {
return axios.get('url')
.then(response => response.data)
.then(id => this.id = id)
.catch(error => console.log(error))
},
foo: function() {
console.log(this.id)
}
},
mounted: function() {
this.getId().then(() => this.foo())
}
})
there are a lot of things that you can do, I think it's useful to read about Promises in JS, but a simple answer for here:
const app = new Vue({
el: '#app',
data: {
id: null
},
methods: {
getId: function(callback) {
return axios.get('url')
.then(response => response.data)
.then((id) => {
this.id = id
callback()
})
.catch(error => console.log(error))
},
foo: function() {
console.log(this.id)
}
},
mounted: function() {
this.getId(() => {
this.foo()
})
}
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With