简体   繁体   English

Vue.js + axios = 数据未更新

[英]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 ) .我是 Vue.js 的新手,我尝试解决一个看起来太奇怪的问题(至少对我来说)

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

自我的输出

But the Vue console seems like that:但是 Vue 控制台看起来是这样的:

Vue 控制台

Thus, while the created is executed normally, the Vue data is not updated.因此,虽然created正常执行,但Vue data没有更新。

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 AJAX 请求返回数据
  • I have also tried the this instead of the let self = this;我也尝试过this而不是let self = this;

The problem is that you are using arrow function in the created hook.问题是您在created的钩子中使用箭头函数。

You can find the reason in https://v2.vuejs.org/v2/guide/instance.html#Instance-Lifecycle-Hooks ,您可以在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()) .不要在选项属性或回调上使用箭头函数,例如created: () = console.log(this.a)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 .由于箭头函数绑定到父上下文, this不会是您期望的 Vue 实例,通常会导致诸如Uncaught TypeError: Cannot read property of undefinedUncaught TypeError: this.myMethod is not a function

you can either use你可以使用

created() {

or或者

created : function() {

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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