I am new to Vue.js and I try to solve an issue that seems too strange ( at least to me ) .
I have the following code:
import Vue from 'vue/dist/vue.js';
import axios from 'axios';
import './components/top-line';
new Vue(
{
el : '#weatherWidget',
data : {
loading : false,
error: '',
current : null,
daily : null,
},
created : () => {
let self = this;
let form_data = new FormData();
form_data.append( 'action', 'weather_request' );
form_data.append( 's', window.vue_weather.s );
self.loading = true;
self.error = '';
axios
.post( window.vue_weather.ajax_url, form_data )
.then(
response => {
let data = response.data;
self.current = data.data.currently;
self.daily = data.data.daily.data;
self.loading = false;
console.log( self );
}
)
.catch(
error => {
this.error = error;
}
);
},
}
);
And when the created
method is executed, I can see in the console the following output:
But the Vue console seems like that:
Thus, while the created
is executed normally, the Vue
data
is not updated.
Do you think I am doing anything wrong? Unfortunately, I cannot see something wrong.
Any solution or idea in order to solve the issue?
NOTES
this
instead of the let self = this;
The problem is that you are using arrow function in the created
hook.
You can find the reason in https://v2.vuejs.org/v2/guide/instance.html#Instance-Lifecycle-Hooks ,
Don't use arrow functions on an options property or callback, such as
created: () = console.log(this.a)
orvm.$watch('a', newValue => this.myMethod())
. Since arrow functions are bound to the parent context,this
will not be the Vue instance as you'd expect, often resulting in errors such asUncaught TypeError: Cannot read property of undefined
orUncaught TypeError: this.myMethod is not a function
.
you can either use
created() {
or
created : function() {
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.