vue.js - 通过提供使用异步数据
问题描述
我对提供有疑问。我想通过提供在路由器视图中使用我的数据。当我使用提供数据时,它给了我一个空数组。我如何将它与异步数据一起使用?
<template>
<div class="container">
<the-sidebar></the-sidebar>
<the-main>
<router-view></router-view>
</the-main>
</div>
</template>
export default {
components: {
TheSidebar,
TheMain,
},
data() {
return {
posts: [],
stories: [],
works: [],
};
},
methods: {
async fetchData(resource) {
const res = await fetch("http://localhost:3000/" + resource);
const data = await res.json();
return data;
},
},
async created() {
this.posts = await this.fetchData("posts");
this.stories = await this.fetchData("stories");
this.works = await this.fetchData("works");
},
provide() {
return {
stories: this.stories,
posts: this.posts,
works: this.works,
};
},
};
解决方案
provide
&inject
在 Vue 中不是响应式的。并且不应该用作反应属性。这样做的原因是您可以轻松地更改某些 ChildComponent 中的数据。这将很难在大型应用程序中调试。
https://vuejs.org/v2/api/#provide-inject
注意:提供和注入绑定不是反应性的。这是故意的。但是,如果您传递一个观察到的对象,该对象上的属性确实保持反应性。
有一种变通方法可以让它实际上是反应式的,但如果你正在学习 Vue,那么现在不是这样做的好时机。
建议:对您来说最好的解决方案是使用props
,并将其传递给 ChildComponent,如下所示:
<router-view :stories="stories" :posts="posts" :works="works"></router-view>
只要记住在 ChildComponent 中注册它们:
props: ['stories', 'posts', 'works'],
道具是反应性属性,是为这种用例制作的。
推荐阅读
- c# - 如何从列表框中合并多个pdf文件
- c# - 如果第一行的库存不足,如何从 1 行扣除到具有相同 id 的另一行(FIFO)
- python - 如何在python中将嵌套的if和for循环放入一行
- c - 当数组未完全填充时,内存中分配了什么?( C )
- python - 如何修复“xcor() 缺少 1 个必需的位置参数:Python 中的‘self’错误
- javascript - 表单第二部分中未定义的对象
- python - 有一种方法可以在 VS Code 上启用一条视觉线来显示 PEP8 的限制?
- zurb-foundation - 如何使显示高度小于移动设备上的视口?
- php - MySQL PDO dbname 在 MySQL 升级后停止工作
- vba - 如何添加条件以检查主题行是否不包含某些文本并且收件人是否在组织之外?