javascript - 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中?
解决方案
您不能:从端点获取数据本质上是异步的,并且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);
}
}
}
推荐阅读
- r - r 更改列名列表(如果存在)
- python - Pandas Max Min 之间的索引范围
- mamp - 在 OS X Apache 上为 python2.7 编译的 wsgi_mod.so 未启动
- vba - 是否可以创建一个返回对象的函数?
- sparql - 将 graphdb SPARQL 浏览器与任何端点一起使用
- javascript - 内容安全策略阻止从 CodePen 到 Github 的链接
- sql - 在 Excel 中使用 SQL 组合来自不同位置的文件
- mysql - 删除前几天的记录,但如果全部删除,保留最后 20 条记录
- u-sql - USQL-JsonArray 列爆炸
- mongodb - 通过替换值更新多个字段值 MongoDB