简体   繁体   English

如何在Vue.js中使用从一个挂钩到另一个挂钩的数据?

[英]How to use data from one hook to other hook in Vue.js?

In my vue.js application I send request by axios package in created() hook. 在我的vue.js应用程序中,我通过created()挂钩中的axios包发送请求。 I add response to array called coordinates . 我将响应添加到称为坐标的数组。 I want to use that array outside of created() hook. 我想在created()钩子之外使用该数组。 For example in mounted() hook or in functions which we can set in methods . 例如在mounted()钩子中或在可以在methods设置的函数中。

Right now when I tried to use self.coordinates outside created() hook it return undefined . 现在,当我尝试在created()钩子之外使用self.coordinates它返回undefined When I use this.coordinates it return just [__ob__: Observer] . 当我使用this.coordinates它仅返回[__ob__: Observer] Whats wrong I did? 我怎么了

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]
    },
}

I think instead of mounted , you should use watch . 我认为您应该使用手表代替骑行。 You call some link so it will take time to load that data , watch method will trigger when your data is updated ... 您调用某个链接,因此加载该数据将花费一些时间,watch方法将在您的数据更新时触发...

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

I would prefer "mounted" and move the logic into methods for reusability. 我希望“挂载”并将逻辑移到可重用性的方法中。 The method can be kicked from anywhere afterwards. 此后可以从任何地方踢该方法。 In the example below, I prefered kicking the method direcly. 在下面的示例中,我更喜欢直接踢该方法。 Watchers is another option. 观察者是另一种选择。

Here is the fiddle https://jsfiddle.net/dj79ux5t/2/ 这是小提琴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);
    }
  }
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM