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