Vue何时在created()过程中存储数据?

时间:2019-04-19 22:50:38

标签: javascript vue.js

我正在尝试使用created()方法存储数据,然后使用Mounted()方法访问数据,但是直到之后似乎都没有存储数据。有办法吗?

我已经设置了测试。在created()中运行

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

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

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

然后我被认为相信的mount()来了,接下来我要调用我的方法

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]

有没有办法让我在挂载中加载此数据?

1 个答案:

答案 0 :(得分:0)

您不能:从端点获取数据本质上是异步,并且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);
        }
    }
}