gpt4 book ai didi

javascript - 如何在 Vue.js 中使用从一个钩子(Hook)到另一个钩子(Hook)的数据?

转载 作者:行者123 更新时间:2023-11-30 14:16:08 25 4
gpt4 key购买 nike

在我的 vue.js 应用程序中,我通过 created() Hook 中的 axios 包发送请求。我将响应添加到名为 coordinates 的数组。我想在 created() Hook 之外使用该数组。例如,在 mounted() 钩子(Hook)或我们可以在 methods 中设置的函数中。

现在,当我尝试在 created() 之外使用 self.coordinates 时,它会返回 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]
},
}

最佳答案

我更喜欢“安装”并将逻辑移动到可重用性的方法中。之后可以从任何地方踢该方法。在下面的例子中,我更喜欢直接踢这个方法。观察者是另一种选择。

这是 fiddle https://jsfiddle.net/dj79ux5t/2/

new Vue({
el: '#app',
data() {
return {
coordinates: []
}
},
mounted() {
let self = this;
axios.get('https://api.weather.gov/').then(function (response) {
self.coordinates = response.data;
self.greet();
});
},
methods: {
greet: function () {
console.warn(this.coordinates.status);
}
}
})

关于javascript - 如何在 Vue.js 中使用从一个钩子(Hook)到另一个钩子(Hook)的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53553805/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com