简体   繁体   中英

Vue.js + axios = data not updated

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:

Vue 控制台

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

  • The AJAX Request returns data
  • I have also tried the 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) or vm.$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 as Uncaught TypeError: Cannot read property of undefined or Uncaught 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM