javascript - 如何在 Vue.js 中使用从一个钩子到另一个钩子的数据?
问题描述
在我的vue.js应用程序中,我通过钩子中的axios包发送请求created()
。我添加了对名为坐标的数组的响应。我想在created()
钩子之外使用那个数组。例如在mounted()
钩子或我们可以设置的函数中methods
。
现在,当我尝试使用self.coordinates
外部created()
钩子时,它会返回undefined
。当我使用this.coordinates
它时,只需返回[__ob__: Observer]
. 我做错了什么?
export default {
name: "Map",
data() {
return {
coordinates: [],
}
},
created() {
let self = this;
axios.get('URL').then(function (response) {
let coordinates = [];
for (let i = 0; i < response.data.length; i++) {
coordinates.push([response.data[i]["LATITUDE"], response.data[i]["LONGITUDE"]]);
}
self.coordinates = coordinates;
});
},
mounted() {
console.log(self.coordinates); // undefined
consol.log(this.coordinates); // [__ob__: Observer]
},
}
解决方案
我认为您应该使用 watch 而不是 mount 。您调用一些链接,因此加载该数据需要时间,当您的数据更新时将触发 watch 方法......
watch: {
coordinates: {
handler: function (updateVal, oldVal) {
console.log(updateVal)
},
deep: true
}
},
推荐阅读
- elasticsearch - 基于聚合的 Elasticsearch 查询,获取每个会话的最后一个事件
- java - gson.JsonObject 到 Json.JSONObject 的转换
- php - 如何使用php获取提交表单中的key部分
- reactjs - ReactNative resizeMode:在android中重复不起作用
- jquery - 如果多个文件字段为空,则 JQuery 禁用按钮
- c - 在 C mongoose os 中的特定时间打开 2 个 LED
- javascript - 如何总结从多选下拉框中选择的值?
- javascript - 材料设计中的easyautocomplete
- c# - 将 JsonObject 映射到类 json
- php - 使用 vue-js 和 Laravel 制作表格