首页 > 解决方案 > 通过提供使用异步数据

问题描述

我对提供有疑问。我想通过提供在路由器视图中使用我的数据。当我使用提供数据时,它给了我一个空数组。我如何将它与异步数据一起使用?

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

Vue.js 开发工具

标签: vue.js

解决方案


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

道具是反应性属性,是为这种用例制作的。


推荐阅读