Code Monkey home page Code Monkey logo

Comments (9)

LennonChin avatar LennonChin commented on May 18, 2024 9

@ozguruysal
Use the code I pasted up can recursive the whole levels, then if you use this way you should designate the name option for your custom component to avoid infinite recursion conducting out-of memory problem. the improved code:

return new Promise((resolve, reject) => {
  const {app, router, store} = createApp();
  router.push(context.url);
  router.onReady(() => {
    const matchedComponents = router.getMatchedComponents();
    if (!matchedComponents.length) {
      return reject(new Error('no component matched'));
    }
    // in order to load all promises
    let targetPromises = [];
    // this cache is used to record operated components' keys, avoid infinite recursion
    let keyCache = [];
    const doAsyncData = (component) => {
      if (component.asyncData) {
        targetPromises.push(component.asyncData({
          route: router.currentRoute,
          store
        }));
      }
    };
    const recursive = (component, key) => {
      // if has key, recursived
      if (keyCache.indexOf(key) !== -1) return;
      // cache key
      keyCache.push(key);
      // do async data
      doAsyncData(component);
      // query sub components
      if (component.components) {
        Object.keys(component.components).forEach(key => {
          recursive(component.components[key], key);
        });
      }
    };
    matchedComponents.map(component => {
      recursive(component, component.name);
    });
    Promise.all(targetPromises).then(data => {
      targetPromises = [];
      keyCache = [];
      context.state = store.state;
      resolve(app);
    }).catch(error => {
      targetPromises = [];
      keyCache = [];
      reject(app);
    });
  }, reject);
});

from vue2-ssr-docs.

egoist avatar egoist commented on May 18, 2024 2

Prefetching data in route components and pass them down as props to ( or use vuex in) child components.

from vue2-ssr-docs.

jazoom avatar jazoom commented on May 18, 2024

I wondered this myself a while ago. The answer was to make them child routes in the router and use <router-view></router-view> (can be named or not named) to insert the children where I wanted.

Maybe this should be mentioned in the documentation so others don't need to find out by experimentation as well?

from vue2-ssr-docs.

romandrahan avatar romandrahan commented on May 18, 2024

@jazoom

make them child routes in the router

I'm afraid it looks like hack. I suppose, there must be another workaround, when components is registered in normal way, without adding them to the child routes?

@yyx990803, is there more elegant solution for that?

from vue2-ssr-docs.

LennonChin avatar LennonChin commented on May 18, 2024

I have a hack way to solve this problem, recursive query sub components and pre-fetching their datum, just like code:

// entry-server.js
import { createApp } from './app'
export default context => {
  return new Promise((resolve, reject) => {
    const { app, router, store } = createApp()
    router.push(context.url)
    router.onReady(() => {
      const matchedComponents = router.getMatchedComponents()
      if (!matchedComponents.length) {
        return reject({ code: 404 })
      }
      // used to load Promises
      const targetPromises = [];
      // encapsulate pre-fetch datum function
      const doAsyncData = (component) => {
        if (component.asyncData) {
          targetPromises.push(component.asyncData({
            store,
            route: router.currentRoute
          }));
        }
      };
      // recursive query sub components
      const recursive = (component) => {
        doAsyncData(component);
        if (component.components) {
          Object.keys(component.components).forEach(key => {
            recursive(component.components[key]);
          });
        }
      };
      // call asyncData() in all matched componets
      matchedComponents.map(component => {
        recursive(component);
      });
      Promise.all(targetPromises).then(() => {
        context.state = store.state
        resolve(app)
      }).catch(reject)
    }, reject)
  })
}

but there may be performance issues with this approach, need to discuss.

from vue2-ssr-docs.

ozguruysal avatar ozguruysal commented on May 18, 2024

I was thinking the same solution as @LennonChin but rather then making it recursive just go one level deep. @LennonChin were you able to find another solution or what did you end up with?

from vue2-ssr-docs.

ozguruysal avatar ozguruysal commented on May 18, 2024

@LennonChin thanks for sharing.

from vue2-ssr-docs.

mach-kernel avatar mach-kernel commented on May 18, 2024

The way I went about this was a little bit different. vue-router lets us define props, so in the routes definition something like this can be done:

    {
      path: '/foo/bar',
      component: () => import('...'),
      props: {
        asyncDataHooks: [
          'MyModule/fetchThing'
        ]
      }
    }

Then, in the server entry point:

    let hooks = router.currentRoute.matched.reduce((hooks, cur) => {
      let adh = cur.props.default.asyncDataHooks;
      if (!adh) return hooks;
      return hooks.concat(adh);
    }, []);

    Promise.all(hooks.map((h) => store.dispatch(h)))...

from vue2-ssr-docs.

darkiron avatar darkiron commented on May 18, 2024

good solution but have two question:
how init store in subComponent asyncDate ?
and:
how fetch data action and return one Promise ?

from vue2-ssr-docs.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.