Vue.js + Axios =数据未更新

时间:2018-09-21 10:16:35

标签: javascript vue.js vuejs2

我是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方法时,我可以在控制台中看到以下输出:

The output of the self

但是Vue控制台看起来像这样:

The Vue console

因此,在正常执行created的同时,Vue data不会更新。

您认为我做错了吗?不幸的是,我看不到任何问题。

是否有解决问题的主意?

注释

  • AJAX请求返回数据
  • 我还尝试了this而不是let self = this;

1 个答案:

答案 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 undefinedUncaught TypeError: this.myMethod is not a function之类的错误。

您可以使用

created() {

created : function() {