3👍
Considering you are using ES2015, you can simply use an arrow function to make sure you don’t create a new this
context:
axios.post('/sales/save', this.$data)
.then(response => {
this.$emit('hide');
})
.catch(error => {
console.log('NO ' , error);
});
You can find out more about arrow functions at: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions
4👍
You assume this
refers to Vue instance, but it’s not the case in your callback. You lose the this
reference in a regular function.
You can preserve this
using one of the following solutions:
1) Use arrow function:
methods: {
fetchData: function() {
axios.get('https://jsonplaceholder.typicode.com/posts/1')
.then(text => console.log(this)) // Vue instance
}
}
2) Save this
to a variable:
methods: {
fetchData: function() {
const self = this; // save reference
axios.get('https://jsonplaceholder.typicode.com/posts/1')
.then(function(text) {
console.log(self) // Vue instance; 'this' points to global object (Window)
})
}
}
1👍
The reason the code in your update didn’t work is that your self
is scoped inside mounted()
, but you’re trying to use it inside methods.save()
.
This would work:
methods: {
save() {
var self = this;
axios.post('/sales/save', this.$data)
.then(function (response) {
self.$emit('hide');
})
//...
Or if you’re using an ES6 transpiler you could use arrow functions to avoid the scoping problem altogether (arrow functions don’t bind their own this
.)
methods: {
save() {
axios.post('/sales/save', this.$data)
.then((response) => {
this.$emit('hide');
})