首页 > 解决方案 > 如何在 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]
    },
}

标签: javascriptvue.jsvuejs2

解决方案


我认为您应该使用 watch 而不是 mount 。您调用一些链接,因此加载该数据需要时间,当您的数据更新时将触发 watch 方法......

watch: {
    coordinates: {
      handler: function (updateVal, oldVal) {
        console.log(updateVal)
      },
      deep: true
    }
  },

推荐阅读