I have a Vue JS (Vuetify) App that makes an ajax request that I would like to populate a div's content with the response, however I am having difficulties accessing the instance's data. All examples I have seen use this to point to the data object, but when I do I get this error
Unable to set property 'message' of undefined or null reference
The app is quite simple:
main.js:
import Vue from 'vue'
import App from './App.vue'
import Vuetify from 'vuetify'
Vue.use(Vuetify)
new Vue({
el: '#app',
render: h => h(App)
})
App.vue
export default {
data () {
return {
....
message: '',
order: {},
...
},
methods: {
send: function() {
axios.post(this.api+"orders",this.order).then(function(response) {
this.message = "Your payment was successful";
...
}
}
}
this.order is accessible without a problem with Axios' post method however the anonymous function that handles the promise returned seems to have a problem accessing this.message, in contrary to the examples I have seen.
What is it that I am doing differently here?
Your problem is this line
Examples may use
this
as you say however, by using a second level of nested function expression, you are accessing a different dynamicthis
than you think you are.Basically,
send
is the method of the Vue object, but sincethis
is not lexically scoped inside offunction
expressions, only inside of=>
functions, you have the wrongthis
reference in the callback you are passing toPromise.prototype.then
.Here is a breakdown:
Try this instead
or better yet
Note in the second example, which uses JavaScript's recently standardized
async/await
functionality, we have abstracted away the need for a callback entirely so the point becomes moot.I suggest it here, not because it relates to your question, but rather because it should be the preferred way of writing Promise driven code if you have it available which you do based on your use of other language features. It leads to clearer code when using Promises.
The key point of this answer however, is the scoping of the
this
reference.I can think of these solutions for your problem.
1) You can create a reference to
this
and use it.2) An
arrow function
will enable you to usethis
which will point to your Vue instance.3) Use
bind
to assign an object tothis
which will be the current Vue instance in your case.