我之前处理过这个“问题”,但我真的不记得如何正确获得结果。我正在使用 Vue 2 在我可以在 HTML 端加载的变量中加载一些数据:
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;
});
}
}
});
如果我console.log(response.data)
在 Axios 函数作用域 (FC) 中写入,它会打印:
但是如果我写console.log(response.data)
在created_ function() {}
范围内,它会打印:
我已经尝试过像这样使用它:
axios.post('/api/operaciones')
.then(response => {
console.log(response.data);
app.operaciones = response.data
})
和
var $this = this;
axios.post('/api/operaciones')
.then(response => {
console.log(response.data);
$this.operaciones = response.data
})
但是是一样的,有什么线索吗?
提前致谢。
这实际上是一个与范围不同的问题。您在问题中尝试的任何解决方案都可以正确设置this.operaciones
. 问题是您正在处理异步操作。
线
console.log(this.operaciones);
increated
将始终记录一个空数组。那是因为loadOperationTypes
执行了异步操作;意思是需要时间。
您似乎期望 in 中的所有内容loadOperationTypes
都会在console.log
执行之前完成,但事实并非如此。loadOperationTypes
将向post
服务器发起,然后代码将继续并执行console.log
.
一旦在稍后的时间点收到来自服务器operaciones
的响应,就会填充响应。
console.clear()
const app = new Vue({
el: '#app',
data: {
operaciones: [],
sopts: []
},
created: function() {
this.loadOperationTypes();
console.log("THIS WILL ALWAYS BE AN EMPTY ARRAY", this.operaciones);
},
methods: {
loadOperationTypes: function() {
axios.post('https://httpbin.org/post', ["some", "data"])
.then(response => {
console.log("THIS SHOULD HAVE DATA", response.data.json);
this.operaciones = response.data.json
})
.catch(error => {
this.operaciones = error;
});
}
},
watch: {
operaciones(newVal){
console.log("THIS WILL HAVE DATA WHEN operaciones IS POPULATED", newVal)
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.17.1/axios.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.9/vue.js"></script>
<div id="app"></div>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句