【问题标题】:Value not updating from axios response in vue值未从 vue 中的 axios 响应更新
【发布时间】:2020-07-22 02:05:17
【问题描述】:

我无法在 axios 调用后更新对象 temp。

请帮忙。

这是完整的代码。我在 vue 中使用过该组件。我对 vue 和组件非常陌生。

下面是app.js

require('./bootstrap');

window.Vue = require('vue');

import axios from 'axios';
window.axios = axios;

Vue.component('shipping-address', require('./components/ShippingAddress.vue'));

const app = new Vue({
    el: '#app',
});
export default app;
<div id="app">
    <shipping-address ></shipping-address>
</div>
<template>
  <div>
    SName: <span>{{temp}}</span>                    
  </div>
</template>
<script>
export default {
  data(){
    return{
        temp:'a'
    }
  },
  mounted(){
      this.fetchArticles();
  },
  methods:{
      fetchArticles() {
          this.temp = 'b'
          const vm = this;
            axios.get('user/addresses')
            .then(response=>{this.temp = 'c';})
            .catch( error => console.log(error));
        },
  }
}
</script>

【问题讨论】:

  • .then(response =&gt; { vm.temp = 'c' });你不能返回一个变量赋值,把你的代码放在括号中,使箭头函数运行一个函数而不是返回一个表达式。
  • 我在这里看到了一些问题。除了答案中的建议外,您应该将mounted() 函数设为async 并在axios 调用之前添加await
  • 仅当您将来自 axios 的响应分配给挂载函数范围内的变量时。使用 .then().catch() 并在回调函数中处理变量赋值应该可以在没有 async/await 语法的情况下工作。
  • 可能不好,没有考虑承诺语法。也不需要将 this 分配给另一个 const vm 并使用它。如果使用数组函数,函数内的this 将附加到上下文中。你应该在挂载的函数中使用 add debugger; 并在 vue 开发工具中查看发生了什么。
  • 我已经修改了代码。请再检查一次。我正在使用该组件。此外,在 Chrome 开发人员工具的 Vue 选项卡中,我只将组件视为 Root,而无法在根目录中看到 Shipping Address 其他组件。请帮忙

标签: vue.js axios


【解决方案1】:

我解决了答案。

我错误地包含了 app.js 两次。一个在页脚刀片文件中,一个在刀片文件本身中。

【讨论】:

    猜你喜欢
    • 2021-11-14
    • 1970-01-01
    • 1970-01-01
    • 2020-08-19
    • 2019-07-30
    • 1970-01-01
    • 1970-01-01
    • 2021-04-12
    • 1970-01-01
    相关资源
    最近更新 更多