Javascript Vue.js 2&;Axios范围问题
我以前处理过这个“问题”,但我真的不记得如何得到正确的结果。我正在使用Vue 2在变量中加载一些数据,我可以在HTML端加载这些数据:Javascript Vue.js 2&;Axios范围问题,javascript,jquery,vue.js,vuejs2,Javascript,Jquery,Vue.js,Vuejs2,我以前处理过这个“问题”,但我真的不记得如何得到正确的结果。我正在使用Vue 2在变量中加载一些数据,我可以在HTML端加载这些数据: window.Vue = require('vue'); window.axios = require('axios'); const app = new Vue({ el: '#app', data: { operaciones: [], sopts: [] }, created: functi
window.Vue = require('vue');
window.axios = require('axios');
const app = new Vue({
el: '#app',
data: {
operaciones: [],
sopts: []
},
created: function() {
this.loadOperationTypes();
console.log(this.operaciones); <-- SC
},
methods: {
loadOperationTypes: function() {
axios.post('/api/operaciones')
.then(response => {
console.log(response.data); <-- FC
this.operaciones = response.data
})
.catch(error => {
this.operaciones = error;
});
}
}
});
及
但是是一样的,有什么线索吗
提前感谢。这实际上是一个与范围无关的问题。您在问题中尝试的任何解决方案都可以正确设置
this.operaciones
。问题是您正在处理一个异步操作
线路
console.log(this.operaciones);
在中创建的将始终记录一个空数组。这是因为loadOperationTypes
执行异步操作;意味着这需要时间
您似乎期望loadOperationTypes
中的所有内容都将在执行console.log
之前完成,但事实并非如此loadOperationTypes
将启动post
到服务器,然后代码将继续并执行console.log
在稍后时间点从服务器接收到响应后,operaciones
将使用响应填充
console.clear()
const app=新的Vue({
el:“#应用程序”,
数据:{
运营商:[],
sopts:[]
},
已创建:函数(){
此参数为.loadOperationTypes();
log(“这将始终是一个空数组”,THIS.operaciones);
},
方法:{
loadOperationTypes:函数(){
轴心柱https://httpbin.org/post“,[“一些”,“数据”])
。然后(响应=>{
log(“这应该有数据”,response.DATA.json);
this.operaciones=response.data.json
})
.catch(错误=>{
this.operaciones=错误;
});
}
},
观察:{
操作系统(newVal){
log(“填充operaciones时将有数据”,newVal)
}
}
});代码>
我完全忘记了,我现在与Vue Inspector进行了检查,所有信息似乎都在那里。非常感谢。
var $this = this;
axios.post('/api/operaciones')
.then(response => {
console.log(response.data);
$this.operaciones = response.data
})
console.log(this.operaciones);