[英]Vue.js + axios = data not updated
我是 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;
問題是您在created
的鈎子中使用箭頭函數。
您可以在https://v2.vuejs.org/v2/guide/instance.html#Instance-Lifecycle-Hooks中找到原因,
不要在選項屬性或回調上使用箭頭函數,例如
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() {
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.