1

I have a Vue app where I am using beforeRouteEnter to load data, and avoid a "flash of unloaded content". On some pages, this is easy:

 async beforeRouteEnter(to, from, next) {
    const newestPosts = await getNewestPosts();
    next(vm => vm.posts = newestPosts);
}

But it's not clear how to get this working when the data lives in child components of the page.

Lets say I have a structure like this

<search-page>
  <posts-list :query="$params.query">
  </posts-list>
</search-page>

Where <posts-list> has all the logic for querying for posts. It's used to build the "related posts" box, or the main search page - or shown on a user's profile page. It's nifty to have it encapsulate the fetching and rendering logic.

I wish I could do something in my beforeRouteEnter like:

 async beforeRouteEnter(to, from, next) {
    await this.$refs.postsList.finishedPromise;
    next();
}

But instead it looks like I'll have to put all the fetching logic in the beforeRouteEnter function. But that means I have to do that for potentially every page - removing some of the utility of the <post-list> component. Is that the only valid solution? I can't quite figure out if vuex would be a solution here. I understand how vuex helps with state (EG "sidebar.open") but could it help with managing search results, in a way that lets me leave the fetching logic in <post-list>?

Penny Liu
  • 15,447
  • 5
  • 79
  • 98
yathern
  • 319
  • 1
  • 3
  • 14

1 Answers1

0

If the data needed to fetch the posts is contained in $params.query, one approach is to watch your query prop inside the posts-list component. When a change is seen, posts-list can determine whether it represents cause for fetching and perform that asynchronously after setting some kind of loading placeholder, like a nifty skeleton loader, which is a nice visual compromise for empty state.

I would avoid trying to interfere with routing changes, and rather think of how to watch for them with reactive logic in the component that "needs to know".

tony19
  • 125,647
  • 18
  • 229
  • 307
Noah Stahl
  • 6,905
  • 5
  • 25
  • 36