我是Vue.js的新手,我试图解决一个似乎太奇怪的问题(至少对我来说)。
我有以下代码:
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;
}
);
},
}
);
执行created
方法时,我可以在控制台中看到以下输出:
但是Vue控制台看起来像这样:
因此,在正常执行created
的同时,Vue
data
不会更新。
您认为我做错了吗?不幸的是,我看不到任何问题。
是否有解决问题的主意?
注释
this
而不是let self = this;
答案 0 :(得分:3)
问题是您在created
钩中使用了箭头功能。
您可以在https://vuejs.org/v2/guide/instance.html#Instance-Lifecycle-Hooks中找到原因,
请勿在options属性或回调中使用箭头功能,例如
created: () = console.log(this.a)
或vm.$watch('a', newValue => this.myMethod())
。由于箭头功能绑定到父级 上下文中,this
通常不是您所期望的Vue实例 导致出现诸如Uncaught TypeError: Cannot read property of undefined
或Uncaught TypeError: this.myMethod is not a function
之类的错误。
您可以使用
created() {
或
created : function() {