首页 > 解决方案 > Vue 在 created() 过程中什么时候存储数据?

问题描述

我正在尝试使用 created() 方法存储数据,然后使用 mount() 方法访问它,但数据似乎直到之后才被存储。有没有办法做到这一点?

我已经设置了一个测试。在 created() 我跑

created() {
            this.getCountriesList();
        },

这会执行 axios 调用以获取国家/地区,然后将它们保存到数据中

getCountriesList() {
                axios.get('https://restcountries.eu/rest/v2/all?fields=name')
                .then(axiosResult => this.countrydata = axiosResult.data) 
            },

然后在我被引导相信的mounted()中,接下来我正在调用我的方法

mounted() {
            this.countryFilteredList()

        }

该方法只是一个console.log

countryFilteredList() {
                console.log(this.countrydata);
            },

这返回

[__ob__: Observer]
length: 0
__ob__: Observer {value: Array(0), dep: Dep, vmCount: 0}
__proto__: Array

但是如果我创建一个单击调用相同 countryFilteredList() 的按钮,我会得到这个

(250) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, …]
[0 … 99]
[100 … 199]
[200 … 249]

有没有办法可以让这些数据加载到mounted中?

标签: javascriptvue.js

解决方案


您不能:从端点获取数据本质上是异步的,并且mounted()生命周期挂钩不能保证数据已被获取。您应该做的只是简单地放置一个观察者this.countrydata,然后在它被填充后对其进行操作。

data: function() {
    return {
        countryData: []
    };  
},
created() {
    this.getCountriesList();
},
methods: {
    getCountriesList() {
        axios.get('https://restcountries.eu/rest/v2/all?fields=name')
        .then(axiosResult => this.countrydata = axiosResult.data);
    }
},
watch: {
    countryData: function(data) {
        if (data.length) {
            console.log(data);
        }
    }
}

推荐阅读