{"id":13827019,"url":"https://github.com/badrap/preload","last_synced_at":"2025-07-09T02:33:10.982Z","repository":{"id":33659958,"uuid":"157611466","full_name":"badrap/preload","owner":"badrap","description":"Data preloading for vue-router, similar to Sapper's preload or Nuxt.js's asyncData","archived":true,"fork":false,"pushed_at":"2023-07-19T01:12:06.000Z","size":2879,"stargazers_count":51,"open_issues_count":23,"forks_count":3,"subscribers_count":6,"default_branch":"master","last_synced_at":"2024-08-04T09:06:09.768Z","etag":null,"topics":["javascript","vue"],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/badrap.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null}},"created_at":"2018-11-14T21:10:59.000Z","updated_at":"2023-08-17T16:11:15.000Z","dependencies_parsed_at":"2024-01-18T04:09:19.390Z","dependency_job_id":"3229ee41-0c1e-4f1d-9a34-1c51ef7e33c1","html_url":"https://github.com/badrap/preload","commit_stats":{"total_commits":61,"total_committers":3,"mean_commits":"20.333333333333332","dds":"0.032786885245901676","last_synced_commit":"743acaf75e9c28fa2abd9071571d9211feb61fc1"},"previous_names":[],"tags_count":12,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/badrap%2Fpreload","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/badrap%2Fpreload/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/badrap%2Fpreload/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/badrap%2Fpreload/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/badrap","download_url":"https://codeload.github.com/badrap/preload/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":225481155,"owners_count":17481160,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["javascript","vue"],"created_at":"2024-08-04T09:01:48.527Z","updated_at":"2024-11-20T06:30:43.567Z","avatar_url":"https://github.com/badrap.png","language":"JavaScript","funding_links":[],"categories":["JavaScript"],"sub_categories":[],"readme":"# @badrap/preload [![tests](https://github.com/badrap/preload/workflows/tests/badge.svg)](https://github.com/badrap/preload/actions?query=workflow%3Atests) [![npm](https://img.shields.io/npm/v/@badrap/preload.svg)](https://www.npmjs.com/package/@badrap/preload)\n\nAdd a `preload` function to your [vue-router](https://router.vuejs.org/) route components, used for prepopulating data before those routes get rendered. Mostly modeled after Sapper's [`preload`](https://sapper.svelte.technology/guide#preloading), but also similar to Nuxt.js's [`asyncData`](https://nuxtjs.org/guide/async-data) and Next.js's [`getInitialProps`](https://nextjs.org/docs/#fetching-data-and-component-lifecycle).\n\n## Installation\n\n```sh\n$ npm i @badrap/preload\n```\n\n## Usage\n\nA modified of the following examples is available at [CodeSandbox](https://codesandbox.io/s/zywnmy35x?initialpath=%23%2Ffoo).\n\n### Basic Setup\n\nThis module exports a single function. Use this function to decorate your route definitions before passing them to vue-router:\n\n```js\nimport Vue from \"vue\";\nimport VueRouter from \"vue-router\";\nimport preload from \"@badrap/preload\"; // Import preload.\nimport Foo from \"./Foo.vue\"; // Import a couple of route components which\nimport Bar from \"./Bar.vue\"; // we decorate with preload.\n\nVue.use(VueRouter);\n\nconst routes = preload([\n  // Use preload here to decorate the route components...\n  { path: \"/foo\", component: Foo },\n  { path: \"/bar\", component: Bar },\n]);\n\nconst router = new VueRouter({\n  routes, // ...and pass them to vue-router.\n});\n\nnew Vue({\n  router,\n  template: \"\u003crouter-view /\u003e\",\n}).$mount(\"#app\");\n```\n\n### Adding Preloading to Components\n\nAfter this setup dance the route components **Foo** and **Bar** can define a new method `preload` that is used to prepopulate their data whenever their route gets rendered - on initial render as well as route changes.\n\nLet's define **Foo** in **Foo.vue**:\n\n```vue\n\u003ctemplate\u003e\n  \u003cdiv\u003e{{ greeting }}, {{ ip }}!\u003c/div\u003e\n\u003c/template\u003e\n\n\u003cscript\u003e\nimport axios from \"axios\";\n\nexport default {\n  async preload() {\n    const { data } = await axios.get(\"https://api.ipify.org\");\n    return { ip: data };\n  },\n  data() {\n    return { greeting: \"Hello\" };\n  },\n};\n\u003c/script\u003e\n```\n\nRendering the route **/foo** would then show a div with the text _\"Hello, 127.0.0.1!\"_, or whatever your IP address happens to be instead of 127.0.0.1. This demonstrates two things:\n\n- The properties returned by `preload` get combined with the properties returned by `data`.\n- `preload` can be asynchronous (it doesn't have to, though).\n\n### Context\n\nThe `preload` method gets a context object that contains useful information and helpers:\n\n| Context property | Meaning                                                                                                                                                                                                                  |\n| ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |\n| `route`          | The [route object](https://router.vuejs.org/api/#the-route-object) for the route that's currently being rendered.                                                                                                        |\n| `redirect`       | A function whose return value you can return from `preload` to redirect the router to. Takes a [location descriptor](https://router.vuejs.org/guide/essentials/navigation.html#router-push-location-oncomplete-onabort). |\n| `error`          | A function whose return value you can return from `preload` to signal a status error.                                                                                                                                    |\n\nHere's an example that uses all of the above:\n\n```vue\n\u003cscript\u003e\nexport default {\n  async preload({ route, redirect, error }) {\n    const { search } = route.query;\n    if (!search) {\n      return error(400, \"?search= missing\");\n    }\n    return redirect(\n      \"https://google.com/search?q=\" + encodeURIComponent(search)\n    );\n  },\n};\n\u003c/script\u003e\n```\n\nIn addition to these properties you can mix in your own when decorating the route components:\n\n```js\nconst routes = preload(..., {\n  context: {\n    appName: \"My sweet app\"\n  }\n);\n```\n\nAfter this `appName` will be a part of every context object passed to `preload` methods of the decorated route components.\n\n### Hooks\n\nIn addition to extra context properties you can pass in two hooks. The `beforePreload` hook is executed before a route change causes `preload` methods to be called. The `afterPreload` hook gets executed when all of the `preload` calls are done.\n\n```js\nconst routes = preload(..., {\n  beforePreload(() =\u003e {\n    // Start a progress indicator here.\n  }),\n  afterPreload(err =\u003e {\n    // Stop and hide the progress indicator here.\n  })\n);\n```\n\n### Error Component\n\nThe default components that gets shown whenever `preload` returns a `context.error(...)` value can be replaced:\n\n```js\nconst routes = preload(..., {\n  errorComponent: ErrorComponent\n});\n```\n\n## License\n\nThis library is licensed under the MIT license. See [LICENSE](./LICENSE).\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fbadrap%2Fpreload","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fbadrap%2Fpreload","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fbadrap%2Fpreload/lists"}