diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml index 66c268145..e10c85f4f 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.yml +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -9,7 +9,7 @@ body: id: reproduction attributes: label: Reproduction - description: "If possible, provide a boiled down editable reproduction using a service like [JSFiddle](https://jsfiddle.net/posva/3yq6ojLv), Codepen, [CodeSandbox](https://codesandbox.io/s/vue-router-4-reproduction-s1sqc), or a GitHub repository. A failing unit test is even better! Otherwise provide as much information as possible to reproduce the problem. If we can't reproduce the problem, we won't be able to give it a look **and the issue will be converted into a question and moved to discussions**." + description: "If possible, provide a boiled down editable reproduction with the [Vue.js Playground](https://play.vuejs.org/#eNqlVG1P2zAQ/iu3bFKLRuNSEB+yUMEQGpv2gti0L8s+pInbGhLbsp1SVPW/72znrVD4MlVp7Lvn7p67x/EmKFPGwzsdRAErpVAGNpApmhp6ISVsYa5ECYNVRQcJbwFKVIaq1hsSb+ggNrbxpVKGPj7hbeYhPgcJBwgrTYc+3O9LUXEzHLzFsMFBcBjU4cgvNrSUBcZPLTBeHk2vaVEIW+xNTHDrzNK9cKGNEnwxvayUotx4ziBTs4xiUvtgs4F3zhHOq6K4QSdsty4N8Xlinq6ahLeO5VfG78GIsyQgSTD9JHAN16KkMen8L0akM7S0YRd29ywuJk3N2Gqzm+s3ow9Aalztjkk7GJyXn2Vo9ij6jZZCPV4zbfB1WBt93r7So1bNVk/boCvdiNoYamUb2W1DO7jW0h4BunbQTHBdi6LgbIfLcGPbW3qa0T7uw4NDC3HROoI/fkQbry4MyACbE0iJo/BRR37rovpAp8cuuuvBw//i/xaPJo6237Q9jzpTTBrQ1FQSipQvUGKjUV6riXfiEjdPDu5k2mTCYzt5puDOzP6vTptqbyGv2qhMJV4AgmMpN/mkdmCFCJzF2rqDYc1JsDRG6oiQisv7RYgDJB3i/CQ8DsckR7V61pDqcjRT4kHj+g6z13IkwTmCSE5XRohCj1LJXirxDHh+Gp6GR6RgM4LZCeM5XbvcNjV+yVts02g8bHO2eNKk1ZwVVP2QhuFh3Gk2xXvl4YuzGVXRlmi2pNn9HvudXnvKN4pidyvaa86kakHxo7fuq5/f6RrXrbMUeVUg+hXnLdWiqCxHD/tY8Rxp93CO7WenGeOLX/pqbSjXTVOWqJuGwzshL19pvaN7HJ70pqjNY0F1mGl7seANdQj2+vFxM6FyqiKYyDUgWZbD2/F4/MG6SkzH+GgmjBFlBEdjuXZ2meY5km0tWCXhmBamkMJ7fFziOrqgc/wy+8jlpF+5S98RyLKsRyCCMf4mdYZg+w+goli8), or an **editable** and **up to date** [CodeSandbox](https://codesandbox.io/s/vue-router-4-reproduction-s1sqc), Stackblitz, or a GitHub repository. A failing unit test is even better! Otherwise provide as much information as possible to reproduce the problem. If we can't reproduce the problem, we won't be able to give it a look **and the issue will be converted into a question and moved to discussions**." placeholder: Reproduction validations: required: true diff --git a/.github/contributing.md b/.github/contributing.md index 523323d6f..087e09b95 100644 --- a/.github/contributing.md +++ b/.github/contributing.md @@ -126,7 +126,7 @@ If you want to start translating the docs in a _new_ language: 1. Create the corresponding `` sub-folder for your translation. 2. Modify the i18n configuration in the `.vitepress` sub-folder. 3. Translate the docs and run the doc site to self-test locally. -4. Create a checkpoint for your language by running `pnpm run docs:translation-status []`. A checkpoint is the hash and date of the latest commit when you do the translation. The checkpoint information is stored in the status file `packages/docs/.vitepress/translation-status.json`. _It's crucial for long-term maintenance since all the further translation sync-ups are based on their previous checkpoints._ Usually, you can skip the commit argument because the default value is `main`. +4. Create a checkpoint for your language by running `pnpm run docs:translation:update []`. A checkpoint is the hash and date of the latest commit when you do the translation. The checkpoint information is stored in the status file `packages/docs/.vitepress/translation-status.json`. _It's crucial for long-term maintenance since all the further translation sync-ups are based on their previous checkpoints._ Usually, you can skip the commit argument because the default value is `main`. 5. Commit all the changes and create a pull request to our GitHub repo. We will have a paragraph at the top of each translation page that shows the translation status. That way, users can quickly determine if the translation is up-to-date or lags behind the English version. @@ -135,9 +135,9 @@ Speaking of the up-to-date translation, we also need good long-term maintenance 1. See what translation you need to sync up with the original docs. There are two popular ways: 1. Via the [GitHub Compare](https://github.com/vuejs/router/compare/) page, only see the changes in `packages/docs/*` from the checkpoint hash to `main` branch. You can find the checkpoint hash for your language via the translation status file `packages/docs/.vitepress/translation-status.json`. The compare page can be directly opened with the hash as part of the URL, e.g. https://github.com/vuejs/router/compare/e008551...main - 2. Via a local command: `pnpm run docs:compare-to-translate []`. + 2. Via a local command: `pnpm run docs:translation:compare []`. 2. Create your own branch and start the translation update, following the previous comparison. -3. Create a checkpoint for your language by running `pnpm run docs:translation-status []`. +3. Create a checkpoint for your language by running `pnpm run docs:translation:update []`. 4. Commit all the changes and create a pull request to our GitHub repo. @@ -149,7 +149,7 @@ You can also host the translation on your own. To create one, fork our GitHub re - Ensure you maintain the _checkpoint_ properly. Also, ensure the _translation status_ is well-displayed on the top of each translation page. - Utilize the diff result between the latest official repository and your own checkpoint to guide your translation. -Tip: you can add the official repo as a remote to your forked repo. This way, you can still run `pnpm run docs:translation-status []` and `npm run docs:compare-to-translate []` to get the checkpoint and diff result: +Tip: you can add the official repo as a remote to your forked repo. This way, you can still run `pnpm run docs:translation:update []` and `npm run docs:translation:compare []` to get the checkpoint and diff result: ```bash # prepare the upstream remote @@ -157,10 +157,10 @@ git remote add upstream git@github.com:vuejs/router.git git fetch upstream main # set the checkpoint -pnpm run docs:translation-status upstream/main +pnpm run docs:translation:update upstream/main # get the diff result -pnpm run docs:compare-to-translate upstream/main +pnpm run docs:translation:compare upstream/main ``` diff --git a/.github/workflows/pkg.pr.new.yml b/.github/workflows/pkg.pr.new.yml new file mode 100644 index 000000000..271a46e08 --- /dev/null +++ b/.github/workflows/pkg.pr.new.yml @@ -0,0 +1,44 @@ +name: Publish Any Commit + +on: + pull_request: + branches: main + paths-ignore: + - 'packages/docs/**' + - 'packages/playground/**' + + push: + branches: + - '**' + tags: + - '!**' + paths-ignore: + - 'packages/docs/**' + - 'packages/playground/**' + +jobs: + build: + runs-on: ubuntu-latest + + steps: + - name: Checkout code + uses: actions/checkout@v4 + with: + fetch-depth: 0 + - uses: pnpm/action-setup@v4 + - uses: actions/setup-node@v4 + with: + node-version: lts/* + cache: pnpm + + - name: Install + run: pnpm install --frozen-lockfile + + - name: Build + run: pnpm -C packages/router build + + - name: Build DTS + run: pnpm -C packages/router build:dts + + - name: Release + run: pnpm dlx pkg-pr-new publish --compact --pnpm './packages/*' diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 97255b0bf..e960d8a57 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -2,10 +2,14 @@ name: test on: push: + branches: + - main paths-ignore: - 'packages/docs/**' - 'packages/playground/**' pull_request: + branches: + - main paths-ignore: - 'packages/docs/**' - 'packages/playground/**' @@ -15,14 +19,12 @@ jobs: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v3 - - uses: pnpm/action-setup@v2 + - uses: actions/checkout@v4 + - uses: pnpm/action-setup@v4 + - uses: actions/setup-node@v4 with: - version: 8.5.0 - - uses: actions/setup-node@v3 - with: - node-version: '18' - cache: 'pnpm' + node-version: 'lts/*' + cache: pnpm - name: 'BrowserStack Env Setup' uses: 'browserstack/github-actions/setup-env@master' # forks do not have access to secrets so just skip this @@ -33,16 +35,17 @@ jobs: - run: pnpm install - run: pnpm run lint - - run: pnpm run -r test:types - - run: pnpm run -r test:unit - run: pnpm run -r build - run: pnpm run -r build:dts - - run: pnpm run -r test:dts + - run: pnpm run -r test:types + - run: pnpm run -r test:unit # e2e tests that that run locally - run: pnpm run -r test:e2e:ci - - uses: codecov/codecov-action@v2 + - uses: codecov/codecov-action@v4 + with: + token: ${{ secrets.CODECOV_TOKEN }} # - name: 'Start BrowserStackLocal Tunnel' # uses: 'browserstack/github-actions/setup-local@master' diff --git a/README.md b/README.md index 578d76d97..b47ebb527 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# vue-router [![release candidate](https://img.shields.io/npm/v/vue-router.svg)](https://www.npmjs.com/package/vue-router) [![test](https://github.com/vuejs/router/actions/workflows/test.yml/badge.svg)](https://github.com/vuejs/router/actions/workflows/test.yml) +# vue-router [![release candidate](https://img.shields.io/npm/v/vue-router.svg)](https://www.npmjs.com/package/vue-router) [![test](https://github.com/vuejs/router/actions/workflows/test.yml/badge.svg)](https://github.com/vuejs/router/actions/workflows/test.yml) [![codecov](https://codecov.io/gh/vuejs/router/graph/badge.svg?token=azNM3FI0d1)](https://codecov.io/gh/vuejs/router) > - This is the repository for Vue Router 4 (for Vue 3) > - For Vue Router 3 (for Vue 2) see [vuejs/vue-router](https://github.com/vuejs/vue-router). @@ -14,10 +14,10 @@ Vue Router is part of the Vue Ecosystem and is an MIT-licensed open source proje

Silver Sponsors

- + - - VueMastery + + Route Optimizer and Route Planner Software @@ -26,32 +26,38 @@ Vue Router is part of the Vue Ecosystem and is an MIT-licensed open source proje Prefect + + + + VueMastery + +

Bronze Sponsors

- + - - Stanislas Ormières + + Storyblok - + - - Antony Konstantinidis + + Nuxt UI Pro Templates - + - - Storyblok + + Antony Konstantinidis - + - - Nuxt UI Pro Templates + + Stanislas Ormières

diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 000000000..c0ca86836 --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,5 @@ +# Reporting a Vulnerability + +To report a vulnerability, please email security@vuejs.org. + +While the discovery of new vulnerabilities is rare, we also recommend always using the latest versions of Vue and its official companion libraries to ensure your application remains as secure as possible. diff --git a/codecov.yml b/codecov.yml new file mode 100644 index 000000000..74aac0d3f --- /dev/null +++ b/codecov.yml @@ -0,0 +1,6 @@ +coverage: + status: + patch: off + project: + default: + threshold: 2% diff --git a/package.json b/package.json index 7fa38fa00..08e089df5 100644 --- a/package.json +++ b/package.json @@ -1,9 +1,9 @@ { "name": "@vue/router-root", "private": true, - "packageManager": "pnpm@8.10.2", + "packageManager": "pnpm@9.10.0", "engines": { - "node": ">=18.14.0" + "node": ">=20.9.0" }, "workspaces": [ "packages/*" @@ -15,8 +15,9 @@ "build:dts": "pnpm run -r build:dts", "docs": "pnpm run --filter ./packages/docs -r docs", "docs:api": "pnpm run --filter ./packages/docs -r docs:api", - "docs:compare-to-translate": "pnpm run --filter ./packages/docs -r docs:compare-to-translate", - "docs:translation-status": "pnpm run --filter ./packages/docs -r docs:translation-status", + "docs:translation:compare": "pnpm run --filter ./packages/docs -r docs:translation:compare", + "docs:translation:update": "pnpm run --filter ./packages/docs -r docs:translation:update", + "docs:translation:status": "pnpm run --filter ./packages/docs -r docs:translation:status", "docs:build": "pnpm run docs:api && pnpm run --filter ./packages/docs -r docs:build", "docs:preview": "pnpm run --filter ./packages/docs -r docs:preview", "play": "pnpm run -r play", @@ -31,16 +32,16 @@ "brotli": "^1.3.3", "chalk": "^5.3.0", "enquirer": "^2.4.1", - "execa": "^8.0.1", - "globby": "^14.0.0", - "lint-staged": "^15.2.0", + "execa": "^9.3.1", + "globby": "^14.0.2", + "lint-staged": "^15.2.10", "minimist": "^1.2.8", "p-series": "^3.0.0", "prettier": "^2.8.8", - "semver": "^7.5.4", - "typedoc": "^0.25.3", + "semver": "^7.6.3", + "typedoc": "^0.25.8", "typedoc-plugin-markdown": "^3.17.1", - "typescript": "~5.1.6", + "typescript": "~5.3.3", "yorkie": "^2.0.0" }, "gitHooks": { @@ -65,6 +66,6 @@ } }, "volta": { - "node": "18.16.0" + "node": "20.11.1" } } diff --git a/packages/docs/.vitepress/config/en.ts b/packages/docs/.vitepress/config/en.ts index 70042ff08..b4e7f0e4b 100644 --- a/packages/docs/.vitepress/config/en.ts +++ b/packages/docs/.vitepress/config/en.ts @@ -46,7 +46,7 @@ export const enConfig: LocaleSpecificConfig = { }, { text: 'Vue.js Certification', - link: 'https://certification.vuejs.org/?friend=VUEROUTER', + link: 'https://certificates.dev/vuejs/?friend=VUEROUTER&utm_source=router_vuejs&utm_medium=link&utm_campaign=router_vuejs_links&utm_content=navbar', }, ], }, @@ -70,7 +70,6 @@ export const enConfig: LocaleSpecificConfig = { }, { text: 'Essentials', - collapsible: false, items: [ { text: 'Getting Started', @@ -84,6 +83,10 @@ export const enConfig: LocaleSpecificConfig = { text: "Routes' Matching Syntax", link: '/guide/essentials/route-matching-syntax.html', }, + { + text: 'Named Routes', + link: '/guide/essentials/named-routes.html', + }, { text: 'Nested Routes', link: '/guide/essentials/nested-routes.html', @@ -92,10 +95,6 @@ export const enConfig: LocaleSpecificConfig = { text: 'Programmatic Navigation', link: '/guide/essentials/navigation.html', }, - { - text: 'Named Routes', - link: '/guide/essentials/named-routes.html', - }, { text: 'Named Views', link: '/guide/essentials/named-views.html', @@ -108,6 +107,10 @@ export const enConfig: LocaleSpecificConfig = { text: 'Passing Props to Route Components', link: '/guide/essentials/passing-props.html', }, + { + text: 'Active links', + link: '/guide/essentials/active-links.html', + }, { text: 'Different History modes', link: '/guide/essentials/history-mode.html', @@ -116,7 +119,6 @@ export const enConfig: LocaleSpecificConfig = { }, { text: 'Advanced', - collapsible: false, items: [ { text: 'Navigation guards', diff --git a/packages/docs/.vitepress/config/shared.ts b/packages/docs/.vitepress/config/shared.ts index aff6067c9..ee38ec511 100644 --- a/packages/docs/.vitepress/config/shared.ts +++ b/packages/docs/.vitepress/config/shared.ts @@ -1,4 +1,5 @@ import { defineConfig, HeadConfig } from 'vitepress' +import { zhSearch } from './zh' // TODO: // export const META_IMAGE = 'https://router.vuejs.org/social.png' @@ -143,10 +144,14 @@ export const sharedConfig = defineConfig({ text: 'Suggest changes', }, - algolia: { - appId: 'BTNTW3I1XP', - apiKey: '771d10c8c5cc48f7922f15048b4d931c', - indexName: 'next_router_vuejs', + search: { + provider: 'algolia', + options: { + appId: 'BTNTW3I1XP', + apiKey: '771d10c8c5cc48f7922f15048b4d931c', + indexName: 'next_router_vuejs', + locales: { ...zhSearch }, + }, }, carbonAds: { diff --git a/packages/docs/.vitepress/config/zh.ts b/packages/docs/.vitepress/config/zh.ts index 0776b6666..dbc6ba4ab 100644 --- a/packages/docs/.vitepress/config/zh.ts +++ b/packages/docs/.vitepress/config/zh.ts @@ -48,20 +48,18 @@ export const zhConfig: LocaleSpecificConfig = { text: '更新日志', link: 'https://github.com/vuejs/router/blob/main/packages/router/CHANGELOG.md', }, + { + text: 'Vue.js 认证', + link: 'https://certificates.dev/vuejs/?friend=VUEROUTER&utm_source=router_vuejs&utm_medium=link&utm_campaign=router_vuejs_links&utm_content=navbar', + }, ], }, ], sidebar: { - '/zh/api/': [ - { - text: 'packages', - items: [{ text: 'vue-router', link: '/zh/api/' }], - }, - ], - '/zh/': [ { + text: '设置', items: [ { text: '介绍', @@ -75,7 +73,6 @@ export const zhConfig: LocaleSpecificConfig = { }, { text: '基础', - collapsible: false, items: [ { text: '入门', @@ -93,14 +90,14 @@ export const zhConfig: LocaleSpecificConfig = { text: '嵌套路由', link: '/zh/guide/essentials/nested-routes.html', }, - { - text: '编程式导航', - link: '/zh/guide/essentials/navigation.html', - }, { text: '命名路由', link: '/zh/guide/essentials/named-routes.html', }, + { + text: '编程式导航', + link: '/zh/guide/essentials/navigation.html', + }, { text: '命名视图', link: '/zh/guide/essentials/named-views.html', @@ -113,6 +110,10 @@ export const zhConfig: LocaleSpecificConfig = { text: '路由组件传参', link: '/zh/guide/essentials/passing-props.html', }, + { + text: '匹配当前路由的链接', + link: '/zh/guide/essentials/active-links.html', + }, { text: '不同的历史记录模式', link: '/zh/guide/essentials/history-mode.html', @@ -121,7 +122,6 @@ export const zhConfig: LocaleSpecificConfig = { }, { text: '进阶', - collapsible: false, items: [ { text: '导航守卫', @@ -139,6 +139,10 @@ export const zhConfig: LocaleSpecificConfig = { text: '组合式 API', link: '/zh/guide/advanced/composition-api.html', }, + { + text: 'RouterView 插槽', + link: '/zh/guide/advanced/router-view-slot.html', + }, { text: '过渡动效', link: '/zh/guide/advanced/transitions.html', @@ -182,6 +186,57 @@ export const zhConfig: LocaleSpecificConfig = { ], }, ], + + '/zh/api/': [ + { + text: 'packages', + items: [{ text: 'vue-router', link: '/zh/api/' }], + }, + ], + }, + }, +} + +export const zhSearch: DefaultTheme.AlgoliaSearchOptions['locales'] = { + zh: { + placeholder: '搜索文档', + translations: { + button: { + buttonText: '搜索文档', + buttonAriaLabel: '搜索文档', + }, + modal: { + searchBox: { + resetButtonTitle: '清除查询条件', + resetButtonAriaLabel: '清除查询条件', + cancelButtonText: '取消', + cancelButtonAriaLabel: '取消', + }, + startScreen: { + recentSearchesTitle: '搜索历史', + noRecentSearchesText: '没有搜索历史', + saveRecentSearchButtonTitle: '保存至搜索历史', + removeRecentSearchButtonTitle: '从搜索历史中移除', + favoriteSearchesTitle: '收藏', + removeFavoriteSearchButtonTitle: '从收藏中移除', + }, + errorScreen: { + titleText: '无法获取结果', + helpText: '你可能需要检查你的网络连接', + }, + footer: { + selectText: '选择', + navigateText: '切换', + closeText: '关闭', + searchByText: '搜索供应商', + }, + noResultsScreen: { + noResultsText: '无法找到相关结果', + suggestedQueryText: '你可以尝试查询', + reportMissingResultsText: '你认为该查询应该有结果?', + reportMissingResultsLinkText: '点击反馈', + }, + }, }, }, } diff --git a/packages/docs/.vitepress/theme/components/AsideSponsors.vue b/packages/docs/.vitepress/theme/components/AsideSponsors.vue index 7066c8bab..edb3e9e2b 100644 --- a/packages/docs/.vitepress/theme/components/AsideSponsors.vue +++ b/packages/docs/.vitepress/theme/components/AsideSponsors.vue @@ -1,6 +1,50 @@ + + diff --git a/packages/docs/.vitepress/theme/components/HomeSponsors.vue b/packages/docs/.vitepress/theme/components/HomeSponsors.vue index 458b02c7d..8bd5f1748 100644 --- a/packages/docs/.vitepress/theme/components/HomeSponsors.vue +++ b/packages/docs/.vitepress/theme/components/HomeSponsors.vue @@ -1,3 +1,16 @@ + + - - + + diff --git a/packages/docs/.vitepress/theme/components/VuejsdeConfBanner.vue b/packages/docs/.vitepress/theme/components/VuejsdeConfBanner.vue new file mode 100644 index 000000000..456242019 --- /dev/null +++ b/packages/docs/.vitepress/theme/components/VuejsdeConfBanner.vue @@ -0,0 +1,102 @@ + + + + + diff --git a/packages/docs/.vitepress/theme/components/sponsors.json b/packages/docs/.vitepress/theme/components/sponsors.json index d4ef1030c..0db6e9928 100644 --- a/packages/docs/.vitepress/theme/components/sponsors.json +++ b/packages/docs/.vitepress/theme/components/sponsors.json @@ -3,31 +3,25 @@ "gold": [], "silver": [ { - "alt": "VueMastery", - "href": "https://www.vuemastery.com/", - "imgSrcDark": "https://posva-sponsors.pages.dev/logos/vuemastery-dark.png", - "imgSrcLight": "https://posva-sponsors.pages.dev/logos/vuemastery-light.svg" + "alt": "Route Optimizer and Route Planner Software", + "href": "https://route4me.com", + "imgSrcDark": "https://posva-sponsors.pages.dev/logos/route4me.png", + "imgSrcLight": "https://posva-sponsors.pages.dev/logos/route4me.png" }, { "alt": "Prefect", "href": "https://www.prefect.io/", "imgSrcDark": "https://posva-sponsors.pages.dev/logos/prefectlogo-dark.svg", "imgSrcLight": "https://posva-sponsors.pages.dev/logos/prefectlogo-light.svg" + }, + { + "alt": "VueMastery", + "href": "https://www.vuemastery.com/", + "imgSrcDark": "https://posva-sponsors.pages.dev/logos/vuemastery-dark.png", + "imgSrcLight": "https://posva-sponsors.pages.dev/logos/vuemastery-light.svg" } ], "bronze": [ - { - "alt": "Stanislas Ormières", - "href": "https://stormier.ninja", - "imgSrcDark": "https://avatars.githubusercontent.com/u/2486424?u=7b0c73ae5d090ce53bf59473094e9606fe082c59&v=4", - "imgSrcLight": "https://avatars.githubusercontent.com/u/2486424?u=7b0c73ae5d090ce53bf59473094e9606fe082c59&v=4" - }, - { - "alt": "Antony Konstantinidis", - "href": "https://www.vuejs.de", - "imgSrcDark": "https://avatars.githubusercontent.com/u/4183726?u=6b50a8ea16de29d2982f43c5640b1db9299ebcd1&v=4", - "imgSrcLight": "https://avatars.githubusercontent.com/u/4183726?u=6b50a8ea16de29d2982f43c5640b1db9299ebcd1&v=4" - }, { "alt": "Storyblok", "href": "https://storyblok.com", @@ -37,8 +31,20 @@ { "alt": "Nuxt UI Pro Templates", "href": "https://ui.nuxt.com/pro", - "imgSrcDark": "https://avatars.githubusercontent.com/u/81570812?v=4", - "imgSrcLight": "https://avatars.githubusercontent.com/u/81570812?v=4" + "imgSrcDark": "https://posva-sponsors.pages.dev/logos/nuxt-dark.svg", + "imgSrcLight": "https://posva-sponsors.pages.dev/logos/nuxt-light.svg" + }, + { + "alt": "Antony Konstantinidis", + "href": "https://www.vuejs.de", + "imgSrcDark": "https://avatars.githubusercontent.com/u/4183726?u=6b50a8ea16de29d2982f43c5640b1db9299ebcd1&v=4", + "imgSrcLight": "https://avatars.githubusercontent.com/u/4183726?u=6b50a8ea16de29d2982f43c5640b1db9299ebcd1&v=4" + }, + { + "alt": "Stanislas Ormières", + "href": "https://stormier.ninja", + "imgSrcDark": "https://avatars.githubusercontent.com/u/2486424?u=7b0c73ae5d090ce53bf59473094e9606fe082c59&v=4", + "imgSrcLight": "https://avatars.githubusercontent.com/u/2486424?u=7b0c73ae5d090ce53bf59473094e9606fe082c59&v=4" } ] } diff --git a/packages/docs/.vitepress/theme/index.ts b/packages/docs/.vitepress/theme/index.ts index c978faf63..25da9d003 100644 --- a/packages/docs/.vitepress/theme/index.ts +++ b/packages/docs/.vitepress/theme/index.ts @@ -1,21 +1,25 @@ import { h } from 'vue' -import { Theme, useData } from 'vitepress' +import { Theme } from 'vitepress' import DefaultTheme from 'vitepress/theme' import AsideSponsors from './components/AsideSponsors.vue' // import HomeSponsors from './components/HomeSponsors.vue' -import TranslationStatus from './components/TranslationStatus.vue' +import TranslationStatus from 'vitepress-translation-helper/ui/TranslationStatus.vue' import './styles/vars.css' -import './styles/sponsors.css' import VueSchoolLink from './components/VueSchoolLink.vue' import VueMasteryLogoLink from './components/VueMasteryLogoLink.vue' +import status from '../translation-status.json' + +const i18nLabels = { + zh: '该翻译已同步到了 ${date} 的版本,其对应的 commit hash 是 ${hash}。', +} const theme: Theme = { - ...DefaultTheme, + extends: DefaultTheme, Layout() { return h(DefaultTheme.Layout, null, { // 'home-features-after': () => h(HomeSponsors), 'aside-ads-before': () => h(AsideSponsors), - 'doc-before': () => h(TranslationStatus), + 'doc-before': () => h(TranslationStatus, { status, i18nLabels }), }) }, diff --git a/packages/docs/.vitepress/theme/styles/sponsors.css b/packages/docs/.vitepress/theme/styles/sponsors.css deleted file mode 100644 index 2929cdc80..000000000 --- a/packages/docs/.vitepress/theme/styles/sponsors.css +++ /dev/null @@ -1,26 +0,0 @@ -.become-sponsor { - font-size: 0.9em; - font-weight: 700; - width: auto; - text-align: center; - background-color: transparent; - padding: 0.75em 2em; - border-radius: 2em; - transition: all 0.15s ease; - box-sizing: border-box; - border: 2px solid var(--vp-c-brand-dark); -} - -.become-sponsor:hover { - background-color: var(--vp-c-brand); - text-decoration: none; - border-color: var(--vp-c-brand); - color: var(--vp-button-brand-text); -} - -.sponsors-top .become-sponsor { - font-size: 0.75em; - padding: 0.2em; - width: auto; - max-width: 150px; -} diff --git a/packages/docs/.vitepress/translation-status.json b/packages/docs/.vitepress/translation-status.json index 1a2101278..85dfe9122 100644 --- a/packages/docs/.vitepress/translation-status.json +++ b/packages/docs/.vitepress/translation-status.json @@ -1,6 +1,6 @@ { "zh": { - "hash": "1a3a28f", - "date": "2023-04-08" + "hash": "d842b6f", + "date": "2024-05-17" } -} +} \ No newline at end of file diff --git a/packages/docs/api/enums/ErrorTypes.md b/packages/docs/api/enums/ErrorTypes.md new file mode 100644 index 000000000..70a03ff2c --- /dev/null +++ b/packages/docs/api/enums/ErrorTypes.md @@ -0,0 +1,40 @@ +--- +editLink: false +--- + +[API Documentation](../index.md) / ErrorTypes + +# Enumeration: ErrorTypes + +Flags so we can combine them when checking for multiple errors. This is the internal version of +[NavigationFailureType](NavigationFailureType.md). + +## Enumeration Members + +### MATCHER\_NOT\_FOUND + +• **MATCHER\_NOT\_FOUND** = ``1`` + +___ + +### NAVIGATION\_ABORTED + +• **NAVIGATION\_ABORTED** = ``4`` + +___ + +### NAVIGATION\_CANCELLED + +• **NAVIGATION\_CANCELLED** = ``8`` + +___ + +### NAVIGATION\_DUPLICATED + +• **NAVIGATION\_DUPLICATED** = ``16`` + +___ + +### NAVIGATION\_GUARD\_REDIRECT + +• **NAVIGATION\_GUARD\_REDIRECT** = ``2`` diff --git a/packages/docs/api/index.md b/packages/docs/api/index.md index f52a63a3c..3625e4fb3 100644 --- a/packages/docs/api/index.md +++ b/packages/docs/api/index.md @@ -8,22 +8,40 @@ API Documentation ## Enumerations +- [ErrorTypes](enums/ErrorTypes.md) - [NavigationFailureType](enums/NavigationFailureType.md) ## Interfaces - [HistoryState](interfaces/HistoryState.md) +- [LocationAsRelativeRaw](interfaces/LocationAsRelativeRaw.md) +- [MatcherLocation](interfaces/MatcherLocation.md) +- [MatcherLocationAsPath](interfaces/MatcherLocationAsPath.md) - [NavigationFailure](interfaces/NavigationFailure.md) - [NavigationGuard](interfaces/NavigationGuard.md) - [NavigationGuardNext](interfaces/NavigationGuardNext.md) - [NavigationGuardWithThis](interfaces/NavigationGuardWithThis.md) - [NavigationHookAfter](interfaces/NavigationHookAfter.md) -- [RouteLocation](interfaces/RouteLocation.md) +- [NavigationRedirectError](interfaces/NavigationRedirectError.md) +- [RouteLocationAsPathGeneric](interfaces/RouteLocationAsPathGeneric.md) +- [RouteLocationAsPathTyped](interfaces/RouteLocationAsPathTyped.md) +- [RouteLocationAsRelativeGeneric](interfaces/RouteLocationAsRelativeGeneric.md) +- [RouteLocationAsRelativeTyped](interfaces/RouteLocationAsRelativeTyped.md) +- [RouteLocationGeneric](interfaces/RouteLocationGeneric.md) - [RouteLocationMatched](interfaces/RouteLocationMatched.md) -- [RouteLocationNormalized](interfaces/RouteLocationNormalized.md) -- [RouteLocationNormalizedLoaded](interfaces/RouteLocationNormalizedLoaded.md) +- [RouteLocationNamedRaw](interfaces/RouteLocationNamedRaw.md) +- [RouteLocationNormalizedGeneric](interfaces/RouteLocationNormalizedGeneric.md) +- [RouteLocationNormalizedLoadedGeneric](interfaces/RouteLocationNormalizedLoadedGeneric.md) +- [RouteLocationNormalizedLoadedTyped](interfaces/RouteLocationNormalizedLoadedTyped.md) +- [RouteLocationNormalizedTyped](interfaces/RouteLocationNormalizedTyped.md) - [RouteLocationOptions](interfaces/RouteLocationOptions.md) +- [RouteLocationPathRaw](interfaces/RouteLocationPathRaw.md) +- [RouteLocationResolvedGeneric](interfaces/RouteLocationResolvedGeneric.md) +- [RouteLocationResolvedTyped](interfaces/RouteLocationResolvedTyped.md) +- [RouteLocationTyped](interfaces/RouteLocationTyped.md) - [RouteMeta](interfaces/RouteMeta.md) +- [RouteQueryAndHash](interfaces/RouteQueryAndHash.md) +- [RouteRecordInfo](interfaces/RouteRecordInfo.md) - [RouteRecordMultipleViews](interfaces/RouteRecordMultipleViews.md) - [RouteRecordMultipleViewsWithChildren](interfaces/RouteRecordMultipleViewsWithChildren.md) - [RouteRecordNormalized](interfaces/RouteRecordNormalized.md) @@ -33,24 +51,31 @@ API Documentation - [Router](interfaces/Router.md) - [RouterHistory](interfaces/RouterHistory.md) - [RouterLinkProps](interfaces/RouterLinkProps.md) +- [RouterMatcher](interfaces/RouterMatcher.md) - [RouterOptions](interfaces/RouterOptions.md) - [RouterScrollBehavior](interfaces/RouterScrollBehavior.md) - [RouterViewProps](interfaces/RouterViewProps.md) +- [TypesConfig](interfaces/TypesConfig.md) +- [UseLinkOptions](interfaces/UseLinkOptions.md) +- [UseLinkReturn](interfaces/UseLinkReturn.md) +- [\_PathParserOptions](interfaces/PathParserOptions.md) +- [\_RouteLocationBase](interfaces/RouteLocationBase.md) - [\_RouteRecordBase](interfaces/RouteRecordBase.md) +- [\_RouterLinkI](interfaces/RouterLinkI.md) ## Type Aliases ### LocationQuery -Ƭ **LocationQuery**: `Record`\<`string`, `LocationQueryValue` \| `LocationQueryValue`[]\> +Ƭ **LocationQuery**: `Record`\<`string`, [`LocationQueryValue`](index.md#LocationQueryValue) \| [`LocationQueryValue`](index.md#LocationQueryValue)[]\> -Normalized query object that appears in [RouteLocationNormalized](interfaces/RouteLocationNormalized.md) +Normalized query object that appears in [RouteLocationNormalized](index.md#RouteLocationNormalized) ___ ### LocationQueryRaw -Ƭ **LocationQueryRaw**: `Record`\<`string` \| `number`, `LocationQueryValueRaw` \| `LocationQueryValueRaw`[]\> +Ƭ **LocationQueryRaw**: `Record`\<`string` \| `number`, [`LocationQueryValueRaw`](index.md#LocationQueryValueRaw) \| [`LocationQueryValueRaw`](index.md#LocationQueryValueRaw)[]\> Loose [LocationQuery](index.md#LocationQuery) object that can be passed to functions like [Router.push](interfaces/Router.md#push) and [Router.replace](interfaces/Router.md#replace) or anywhere when creating a @@ -58,9 +83,124 @@ Loose [LocationQuery](index.md#LocationQuery) object that can be passed to funct ___ +### LocationQueryValue + +Ƭ **LocationQueryValue**: `string` \| ``null`` + +Possible values in normalized [LocationQuery](index.md#LocationQuery). `null` renders the query +param but without an `=`. + +**`Example`** + +``` +?isNull&isEmpty=&other=other +gives +`{ isNull: null, isEmpty: '', other: 'other' }`. +``` + +___ + +### LocationQueryValueRaw + +Ƭ **LocationQueryValueRaw**: [`LocationQueryValue`](index.md#LocationQueryValue) \| `number` \| `undefined` + +Possible values when defining a query. + +___ + +### NavigationGuardNextCallback + +Ƭ **NavigationGuardNextCallback**: (`vm`: `ComponentPublicInstance`) => `unknown` + +Callback that can be passed to `next()` in `beforeRouteEnter()` guards. + +#### Type declaration + +▸ (`vm`): `unknown` + +##### Parameters + +| Name | Type | +| :------ | :------ | +| `vm` | `ComponentPublicInstance` | + +##### Returns + +`unknown` + +___ + +### NavigationGuardReturn + +Ƭ **NavigationGuardReturn**: `void` \| `Error` \| `boolean` \| [`RouteLocationRaw`](index.md#RouteLocationRaw) + +Return types for a Navigation Guard. Based on `TypesConfig` + +**`See`** + +[TypesConfig](interfaces/TypesConfig.md) + +___ + +### ParamValue + +Ƭ **ParamValue**\<`isRaw`\>: ``true`` extends `isRaw` ? `string` \| `number` : `string` + +Utility type for raw and non raw params like :id + +#### Type parameters + +| Name | Type | +| :------ | :------ | +| `isRaw` | extends `boolean` | + +___ + +### ParamValueOneOrMore + +Ƭ **ParamValueOneOrMore**\<`isRaw`\>: [[`ParamValue`](index.md#ParamValue)\<`isRaw`\>, ...ParamValue\[]] + +Utility type for raw and non raw params like :id+ + +#### Type parameters + +| Name | Type | +| :------ | :------ | +| `isRaw` | extends `boolean` | + +___ + +### ParamValueZeroOrMore + +Ƭ **ParamValueZeroOrMore**\<`isRaw`\>: ``true`` extends `isRaw` ? [`ParamValue`](index.md#ParamValue)\<`isRaw`\>[] \| `undefined` \| ``null`` : [`ParamValue`](index.md#ParamValue)\<`isRaw`\>[] \| `undefined` + +Utility type for raw and non raw params like :id* + +#### Type parameters + +| Name | Type | +| :------ | :------ | +| `isRaw` | extends `boolean` | + +___ + +### ParamValueZeroOrOne + +Ƭ **ParamValueZeroOrOne**\<`isRaw`\>: ``true`` extends `isRaw` ? `string` \| `number` \| ``null`` \| `undefined` : `string` + +Utility type for raw and non raw params like :id? + +#### Type parameters + +| Name | Type | +| :------ | :------ | +| `isRaw` | extends `boolean` | + +___ + ### PathParserOptions -Ƭ **PathParserOptions**: `Pick`\<`_PathParserOptions`, ``"end"`` \| ``"sensitive"`` \| ``"strict"``\> +Ƭ **PathParserOptions**: `Pick`\<[`_PathParserOptions`](interfaces/PathParserOptions.md), ``"end"`` \| ``"sensitive"`` \| ``"strict"``\> ___ @@ -72,23 +212,307 @@ Allowed Component in [RouteLocationMatched](interfaces/RouteLocationMatched.md) ___ +### RouteLocation + +Ƭ **RouteLocation**\<`Name`\>: [`RouteMapGeneric`](index.md#RouteMapGeneric) extends [`RouteMap`](index.md#RouteMap) ? [`RouteLocationGeneric`](interfaces/RouteLocationGeneric.md) : [`RouteLocationTypedList`](index.md#RouteLocationTypedList)\<[`RouteMap`](index.md#RouteMap)\>[`Name`] + +[RouteLocationRaw](index.md#RouteLocationRaw) resolved using the matcher + +#### Type parameters + +| Name | Type | +| :------ | :------ | +| `Name` | extends keyof [`RouteMap`](index.md#RouteMap) = keyof [`RouteMap`](index.md#RouteMap) | + +___ + +### RouteLocationAsPath + +Ƭ **RouteLocationAsPath**\<`Name`\>: [`RouteMapGeneric`](index.md#RouteMapGeneric) extends [`RouteMap`](index.md#RouteMap) ? [`RouteLocationAsPathGeneric`](interfaces/RouteLocationAsPathGeneric.md) : [`RouteLocationAsPathTypedList`](index.md#RouteLocationAsPathTypedList)\<[`RouteMap`](index.md#RouteMap)\>[`Name`] + +Route location as an object with a `path` property. + +#### Type parameters + +| Name | Type | +| :------ | :------ | +| `Name` | extends keyof [`RouteMap`](index.md#RouteMap) = keyof [`RouteMap`](index.md#RouteMap) | + +___ + +### RouteLocationAsPathTypedList + +Ƭ **RouteLocationAsPathTypedList**\<`RouteMap`\>: \{ [N in keyof RouteMap]: RouteLocationAsPathTyped\ } + +List of all possible [RouteLocationAsPath](index.md#RouteLocationAsPath) indexed by the route name. + +#### Type parameters + +| Name | Type | +| :------ | :------ | +| `RouteMap` | extends [`RouteMapGeneric`](index.md#RouteMapGeneric) = [`RouteMapGeneric`](index.md#RouteMapGeneric) | + +___ + +### RouteLocationAsRelative + +Ƭ **RouteLocationAsRelative**\<`Name`\>: [`RouteMapGeneric`](index.md#RouteMapGeneric) extends [`RouteMap`](index.md#RouteMap) ? [`RouteLocationAsRelativeGeneric`](interfaces/RouteLocationAsRelativeGeneric.md) : [`RouteLocationAsRelativeTypedList`](index.md#RouteLocationAsRelativeTypedList)\<[`RouteMap`](index.md#RouteMap)\>[`Name`] + +Route location relative to the current location. It accepts other properties than `path` like `params`, `query` and +`hash` to conveniently change them. + +#### Type parameters + +| Name | Type | +| :------ | :------ | +| `Name` | extends keyof [`RouteMap`](index.md#RouteMap) = keyof [`RouteMap`](index.md#RouteMap) | + +___ + +### RouteLocationAsRelativeTypedList + +Ƭ **RouteLocationAsRelativeTypedList**\<`RouteMap`\>: \{ [N in keyof RouteMap]: RouteLocationAsRelativeTyped\ } + +List of all possible [RouteLocationAsRelative](index.md#RouteLocationAsRelative) indexed by the route name. + +#### Type parameters + +| Name | Type | +| :------ | :------ | +| `RouteMap` | extends [`RouteMapGeneric`](index.md#RouteMapGeneric) = [`RouteMapGeneric`](index.md#RouteMapGeneric) | + +___ + +### RouteLocationAsString + +Ƭ **RouteLocationAsString**\<`Name`\>: [`RouteMapGeneric`](index.md#RouteMapGeneric) extends [`RouteMap`](index.md#RouteMap) ? `string` : `_LiteralUnion`\<[`RouteLocationAsStringTypedList`](index.md#RouteLocationAsStringTypedList)\<[`RouteMap`](index.md#RouteMap)\>[`Name`], `string`\> + +Same as [RouteLocationAsPath](index.md#RouteLocationAsPath) but as a string literal. + +#### Type parameters + +| Name | Type | +| :------ | :------ | +| `Name` | extends keyof [`RouteMap`](index.md#RouteMap) = keyof [`RouteMap`](index.md#RouteMap) | + +___ + +### RouteLocationAsStringTyped + +Ƭ **RouteLocationAsStringTyped**\<`RouteMap`, `Name`\>: `RouteMap`[`Name`][``"path"``] + +Helper to generate a type safe version of the [RouteLocationAsString](index.md#RouteLocationAsString) type. + +#### Type parameters + +| Name | Type | +| :------ | :------ | +| `RouteMap` | extends [`RouteMapGeneric`](index.md#RouteMapGeneric) = [`RouteMapGeneric`](index.md#RouteMapGeneric) | +| `Name` | extends keyof `RouteMap` = keyof `RouteMap` | + +___ + +### RouteLocationAsStringTypedList + +Ƭ **RouteLocationAsStringTypedList**\<`RouteMap`\>: \{ [N in keyof RouteMap]: RouteLocationAsStringTyped\ } + +List of all possible [RouteLocationAsString](index.md#RouteLocationAsString) indexed by the route name. + +#### Type parameters + +| Name | Type | +| :------ | :------ | +| `RouteMap` | extends [`RouteMapGeneric`](index.md#RouteMapGeneric) = [`RouteMapGeneric`](index.md#RouteMapGeneric) | + +___ + +### RouteLocationNormalized + +Ƭ **RouteLocationNormalized**\<`Name`\>: [`RouteMapGeneric`](index.md#RouteMapGeneric) extends [`RouteMap`](index.md#RouteMap) ? [`RouteLocationNormalizedGeneric`](interfaces/RouteLocationNormalizedGeneric.md) : [`RouteLocationNormalizedTypedList`](index.md#RouteLocationNormalizedTypedList)\<[`RouteMap`](index.md#RouteMap)\>[`Name`] + +Similar to [RouteLocation](index.md#RouteLocation) but its +[`matched` property](interfaces/RouteLocationNormalizedTyped.md#matched) cannot contain redirect records + +#### Type parameters + +| Name | Type | +| :------ | :------ | +| `Name` | extends keyof [`RouteMap`](index.md#RouteMap) = keyof [`RouteMap`](index.md#RouteMap) | + +___ + +### RouteLocationNormalizedLoaded + +Ƭ **RouteLocationNormalizedLoaded**\<`Name`\>: [`RouteMapGeneric`](index.md#RouteMapGeneric) extends [`RouteMap`](index.md#RouteMap) ? [`RouteLocationNormalizedLoadedGeneric`](interfaces/RouteLocationNormalizedLoadedGeneric.md) : [`RouteLocationNormalizedLoadedTypedList`](index.md#RouteLocationNormalizedLoadedTypedList)\<[`RouteMap`](index.md#RouteMap)\>[`Name`] + +Similar to [RouteLocationNormalized](index.md#RouteLocationNormalized) but its `components` do not contain any function to lazy load components. +In other words, it's ready to be rendered by ``. + +#### Type parameters + +| Name | Type | +| :------ | :------ | +| `Name` | extends keyof [`RouteMap`](index.md#RouteMap) = keyof [`RouteMap`](index.md#RouteMap) | + +___ + +### RouteLocationNormalizedLoadedTypedList + +Ƭ **RouteLocationNormalizedLoadedTypedList**\<`RouteMap`\>: \{ [N in keyof RouteMap]: RouteLocationNormalizedLoadedTyped\ } + +List of all possible [RouteLocationNormalizedLoaded](index.md#RouteLocationNormalizedLoaded) indexed by the route name. + +#### Type parameters + +| Name | Type | +| :------ | :------ | +| `RouteMap` | extends [`RouteMapGeneric`](index.md#RouteMapGeneric) = [`RouteMapGeneric`](index.md#RouteMapGeneric) | + +___ + +### RouteLocationNormalizedTypedList + +Ƭ **RouteLocationNormalizedTypedList**\<`RouteMap`\>: \{ [N in keyof RouteMap]: RouteLocationNormalizedTyped\ } + +List of all possible [RouteLocationNormalized](index.md#RouteLocationNormalized) indexed by the route name. + +#### Type parameters + +| Name | Type | +| :------ | :------ | +| `RouteMap` | extends [`RouteMapGeneric`](index.md#RouteMapGeneric) = [`RouteMapGeneric`](index.md#RouteMapGeneric) | + +___ + ### RouteLocationRaw -Ƭ **RouteLocationRaw**: `string` \| `RouteLocationPathRaw` \| `RouteLocationNamedRaw` +Ƭ **RouteLocationRaw**\<`Name`\>: [`RouteMapGeneric`](index.md#RouteMapGeneric) extends [`RouteMap`](index.md#RouteMap) ? [`RouteLocationAsString`](index.md#RouteLocationAsString) \| [`RouteLocationAsRelativeGeneric`](interfaces/RouteLocationAsRelativeGeneric.md) \| [`RouteLocationAsPathGeneric`](interfaces/RouteLocationAsPathGeneric.md) : `_LiteralUnion`\<[`RouteLocationAsStringTypedList`](index.md#RouteLocationAsStringTypedList)\<[`RouteMap`](index.md#RouteMap)\>[`Name`], `string`\> \| [`RouteLocationAsRelativeTypedList`](index.md#RouteLocationAsRelativeTypedList)\<[`RouteMap`](index.md#RouteMap)\>[`Name`] \| [`RouteLocationAsPathTypedList`](index.md#RouteLocationAsPathTypedList)\<[`RouteMap`](index.md#RouteMap)\>[`Name`] + +Route location that can be passed to `router.push()` and other user-facing APIs. + +#### Type parameters + +| Name | Type | +| :------ | :------ | +| `Name` | extends keyof [`RouteMap`](index.md#RouteMap) = keyof [`RouteMap`](index.md#RouteMap) | + +___ + +### RouteLocationResolved + +Ƭ **RouteLocationResolved**\<`Name`\>: [`RouteMapGeneric`](index.md#RouteMapGeneric) extends [`RouteMap`](index.md#RouteMap) ? [`RouteLocationResolvedGeneric`](interfaces/RouteLocationResolvedGeneric.md) : [`RouteLocationResolvedTypedList`](index.md#RouteLocationResolvedTypedList)\<[`RouteMap`](index.md#RouteMap)\>[`Name`] + +Route location resolved with [`router.resolve()`](interfaces/Router.md). + +#### Type parameters + +| Name | Type | +| :------ | :------ | +| `Name` | extends keyof [`RouteMap`](index.md#RouteMap) = keyof [`RouteMap`](index.md#RouteMap) | + +___ + +### RouteLocationResolvedTypedList + +Ƭ **RouteLocationResolvedTypedList**\<`RouteMap`\>: \{ [N in keyof RouteMap]: RouteLocationResolvedTyped\ } + +List of all possible [RouteLocationResolved](index.md#RouteLocationResolved) indexed by the route name. + +#### Type parameters + +| Name | Type | +| :------ | :------ | +| `RouteMap` | extends [`RouteMapGeneric`](index.md#RouteMapGeneric) = [`RouteMapGeneric`](index.md#RouteMapGeneric) | + +___ + +### RouteLocationTypedList + +Ƭ **RouteLocationTypedList**\<`RouteMap`\>: \{ [N in keyof RouteMap]: RouteLocationTyped\ } + +List of all possible [RouteLocation](index.md#RouteLocation) indexed by the route name. + +#### Type parameters + +| Name | Type | +| :------ | :------ | +| `RouteMap` | extends [`RouteMapGeneric`](index.md#RouteMapGeneric) = [`RouteMapGeneric`](index.md#RouteMapGeneric) | + +___ + +### RouteMap + +Ƭ **RouteMap**: [`TypesConfig`](interfaces/TypesConfig.md) extends `Record`\<``"RouteNamedMap"``, infer RouteNamedMap\> ? `RouteNamedMap` : [`RouteMapGeneric`](index.md#RouteMapGeneric) + +Convenience type to get the typed RouteMap or a generic one if not provided. It is extracted from the [TypesConfig](interfaces/TypesConfig.md) if it exists, it becomes [RouteMapGeneric](index.md#RouteMapGeneric) otherwise. + +___ + +### RouteMapGeneric + +Ƭ **RouteMapGeneric**: `Record`\<`string` \| `symbol`, [`RouteRecordInfo`](interfaces/RouteRecordInfo.md)\> + +Generic version of the `RouteMap`. + +___ + +### RouteParamValue + +Ƭ **RouteParamValue**: `string` + +___ + +### RouteParamValueRaw -User-level route location +Ƭ **RouteParamValueRaw**: [`RouteParamValue`](index.md#RouteParamValue) \| `number` \| ``null`` \| `undefined` ___ ### RouteParams -Ƭ **RouteParams**: `Record`\<`string`, `RouteParamValue` \| `RouteParamValue`[]\> +Ƭ **RouteParams**\<`Name`\>: [`RouteMap`](index.md#RouteMap)[`Name`][``"params"``] + +Generate a type safe params for a route location. Requires the name of the route to be passed as a generic. + +**`See`** + +[RouteParamsGeneric](index.md#RouteParamsGeneric) + +#### Type parameters + +| Name | Type | +| :------ | :------ | +| `Name` | extends keyof [`RouteMap`](index.md#RouteMap) = keyof [`RouteMap`](index.md#RouteMap) | + +___ + +### RouteParamsGeneric + +Ƭ **RouteParamsGeneric**: `Record`\<`string`, [`RouteParamValue`](index.md#RouteParamValue) \| [`RouteParamValue`](index.md#RouteParamValue)[]\> ___ ### RouteParamsRaw -Ƭ **RouteParamsRaw**: `Record`\<`string`, `RouteParamValueRaw` \| `Exclude`\<`RouteParamValueRaw`, ``null`` \| `undefined`\>[]\> +Ƭ **RouteParamsRaw**\<`Name`\>: [`RouteMap`](index.md#RouteMap)[`Name`][``"paramsRaw"``] + +Generate a type safe raw params for a route location. Requires the name of the route to be passed as a generic. + +**`See`** + +[RouteParamsRaw](index.md#RouteParamsRaw) + +#### Type parameters + +| Name | Type | +| :------ | :------ | +| `Name` | extends keyof [`RouteMap`](index.md#RouteMap) = keyof [`RouteMap`](index.md#RouteMap) | + +___ + +### RouteParamsRawGeneric + +Ƭ **RouteParamsRawGeneric**: `Record`\<`string`, [`RouteParamValueRaw`](index.md#RouteParamValueRaw) \| `Exclude`\<[`RouteParamValueRaw`](index.md#RouteParamValueRaw), ``null`` \| `undefined`\>[]\> ___ @@ -102,9 +526,19 @@ ___ ### RouteRecordName -Ƭ **RouteRecordName**: `string` \| `symbol` +Ƭ **RouteRecordName**: [`RouteMapGeneric`](index.md#RouteMapGeneric) extends [`RouteMap`](index.md#RouteMap) ? [`RouteRecordNameGeneric`](index.md#RouteRecordNameGeneric) : keyof [`RouteMap`](index.md#RouteMap) + +Possible values for a route record **after normalization** -Possible values for a user-defined route record's name +NOTE: since `RouteRecordName` is a type, it evaluates too early and it's often the generic version [RouteRecordNameGeneric](index.md#RouteRecordNameGeneric). If you need a typed version of all of the names of routes, use [`keyof RouteMap`](index.md#RouteMap) + +___ + +### RouteRecordNameGeneric + +Ƭ **RouteRecordNameGeneric**: `string` \| `symbol` \| `undefined` + +Generic version of [RouteRecordName](index.md#RouteRecordName). ___ @@ -114,15 +548,41 @@ ___ ___ -### UseLinkOptions +### RouteRecordRedirectOption + +Ƭ **RouteRecordRedirectOption**: [`RouteLocationRaw`](index.md#RouteLocationRaw) \| (`to`: [`RouteLocation`](index.md#RouteLocation)) => [`RouteLocationRaw`](index.md#RouteLocationRaw) + +___ + +### \_Awaitable + +Ƭ **\_Awaitable**\<`T`\>: `T` \| `PromiseLike`\<`T`\> + +Maybe a promise maybe not + +#### Type parameters + +| Name | +| :------ | +| `T` | + +___ + +### \_RouteRecordProps + +Ƭ **\_RouteRecordProps**\<`Name`\>: `boolean` \| `Record`\<`string`, `any`\> \| (`to`: [`RouteLocationNormalized`](index.md#RouteLocationNormalized)\<`Name`\>) => `Record`\<`string`, `any`\> -Ƭ **UseLinkOptions**: `VueUseOptions`\<`RouterLinkOptions`\> +#### Type parameters + +| Name | Type | +| :------ | :------ | +| `Name` | extends keyof [`RouteMap`](index.md#RouteMap) = keyof [`RouteMap`](index.md#RouteMap) | ## Variables ### RouterLink -• `Const` **RouterLink**: `_RouterLinkI` +• `Const` **RouterLink**: [`_RouterLinkI`](interfaces/RouterLinkI.md) Component to render a link that triggers a navigation on click. @@ -130,7 +590,9 @@ ___ ### RouterView -• `Const` **RouterView**: () => \{ `$props`: `AllowedComponentProps` & `ComponentCustomProps` & `VNodeProps` & [`RouterViewProps`](interfaces/RouterViewProps.md) ; `$slots`: \{ `default?`: (`__namedParameters`: \{ `Component`: `VNode`\<`RendererNode`, `RendererElement`, \{ `[key: string]`: `any`; }\> ; `route`: [`RouteLocationNormalizedLoaded`](interfaces/RouteLocationNormalizedLoaded.md) }) => `VNode`\<`RendererNode`, `RendererElement`, \{ `[key: string]`: `any`; }\>[] } } +• `Const` **RouterView**: () => \{ `$props`: `AllowedComponentProps` & `ComponentCustomProps` & `VNodeProps` & [`RouterViewProps`](interfaces/RouterViewProps.md) ; `$slots`: \{ `default?`: (`__namedParameters`: \{ `Component`: `VNode`\<`RendererNode`, `RendererElement`, \{ `[key: string]`: `any`; }\> ; `route`: [`RouteLocationNormalizedLoadedGeneric`](interfaces/RouteLocationNormalizedLoadedGeneric.md) }) => `VNode`\<`RendererNode`, `RendererElement`, \{ `[key: string]`: `any`; }\>[] } } + +Component to display the current route the user is at. #### Type declaration @@ -145,14 +607,14 @@ Component to display the current route the user is at. | Name | Type | | :------ | :------ | | `$props` | `AllowedComponentProps` & `ComponentCustomProps` & `VNodeProps` & [`RouterViewProps`](interfaces/RouterViewProps.md) | -| `$slots` | \{ `default?`: (`__namedParameters`: \{ `Component`: `VNode`\<`RendererNode`, `RendererElement`, \{ `[key: string]`: `any`; }\> ; `route`: [`RouteLocationNormalizedLoaded`](interfaces/RouteLocationNormalizedLoaded.md) }) => `VNode`\<`RendererNode`, `RendererElement`, \{ `[key: string]`: `any`; }\>[] } | -| `$slots.default?` | (`__namedParameters`: \{ `Component`: `VNode`\<`RendererNode`, `RendererElement`, \{ `[key: string]`: `any`; }\> ; `route`: [`RouteLocationNormalizedLoaded`](interfaces/RouteLocationNormalizedLoaded.md) }) => `VNode`\<`RendererNode`, `RendererElement`, \{ `[key: string]`: `any`; }\>[] | +| `$slots` | \{ `default?`: (`__namedParameters`: \{ `Component`: `VNode`\<`RendererNode`, `RendererElement`, \{ `[key: string]`: `any`; }\> ; `route`: [`RouteLocationNormalizedLoadedGeneric`](interfaces/RouteLocationNormalizedLoadedGeneric.md) }) => `VNode`\<`RendererNode`, `RendererElement`, \{ `[key: string]`: `any`; }\>[] } | +| `$slots.default?` | (`__namedParameters`: \{ `Component`: `VNode`\<`RendererNode`, `RendererElement`, \{ `[key: string]`: `any`; }\> ; `route`: [`RouteLocationNormalizedLoadedGeneric`](interfaces/RouteLocationNormalizedLoadedGeneric.md) }) => `VNode`\<`RendererNode`, `RendererElement`, \{ `[key: string]`: `any`; }\>[] | ___ ### START\_LOCATION -• `Const` **START\_LOCATION**: [`RouteLocationNormalizedLoaded`](interfaces/RouteLocationNormalizedLoaded.md) +• `Const` **START\_LOCATION**: [`RouteLocationNormalizedLoaded`](index.md#RouteLocationNormalizedLoaded) Initial route location where the router is. Can be used in navigation guards to differentiate the initial navigation. @@ -169,6 +631,52 @@ router.beforeEach((to, from) => { }) ``` +___ + +### matchedRouteKey + +• `Const` **matchedRouteKey**: `InjectionKey`\<`ComputedRef`\<`undefined` \| [`RouteRecordNormalized`](interfaces/RouteRecordNormalized.md)\>\> + +RouteRecord being rendered by the closest ancestor Router View. Used for +`onBeforeRouteUpdate` and `onBeforeRouteLeave`. rvlm stands for Router View +Location Matched + +___ + +### routeLocationKey + +• `Const` **routeLocationKey**: `InjectionKey`\<[`RouteLocationNormalizedLoadedGeneric`](interfaces/RouteLocationNormalizedLoadedGeneric.md)\> + +Allows overriding the current route returned by `useRoute` in tests. rl +stands for route location + +___ + +### routerKey + +• `Const` **routerKey**: `InjectionKey`\<[`Router`](interfaces/Router.md)\> + +Allows overriding the router instance returned by `useRouter` in tests. r +stands for router + +___ + +### routerViewLocationKey + +• `Const` **routerViewLocationKey**: `InjectionKey`\<`Ref`\<[`RouteLocationNormalizedLoadedGeneric`](interfaces/RouteLocationNormalizedLoadedGeneric.md)\>\> + +Allows overriding the current route used by router-view. Internally this is +used when the `route` prop is passed. + +___ + +### viewDepthKey + +• `Const` **viewDepthKey**: `InjectionKey`\<`number` \| `Ref`\<`number`\>\> + +Allows overriding the router view depth to control which component in +`matched` is rendered. rvd stands for Router View Depth + ## Functions ### createMemoryHistory @@ -210,6 +718,25 @@ Creates a Router instance that can be used by a Vue app. ___ +### createRouterMatcher + +▸ **createRouterMatcher**(`routes`, `globalOptions`): [`RouterMatcher`](interfaces/RouterMatcher.md) + +Creates a Router Matcher. + +#### Parameters + +| Name | Type | Description | +| :------ | :------ | :------ | +| `routes` | readonly [`RouteRecordRaw`](index.md#RouteRecordRaw)[] | array of initial routes | +| `globalOptions` | [`PathParserOptions`](index.md#PathParserOptions) | global route options | + +#### Returns + +[`RouterMatcher`](interfaces/RouterMatcher.md) + +___ + ### createWebHashHistory ▸ **createWebHashHistory**(`base?`): [`RouterHistory`](interfaces/RouterHistory.md) @@ -274,7 +801,7 @@ Check if an object is a [NavigationFailure](interfaces/NavigationFailure.md). | Name | Type | Description | | :------ | :------ | :------ | | `error` | `any` | possible [NavigationFailure](interfaces/NavigationFailure.md) | -| `type?` | `NAVIGATION_GUARD_REDIRECT` | optional types to check for | +| `type?` | [`NAVIGATION_GUARD_REDIRECT`](enums/ErrorTypes.md#NAVIGATION_GUARD_REDIRECT) | optional types to check for | #### Returns @@ -308,7 +835,7 @@ router.afterEach((to, from, failure) => { | Name | Type | | :------ | :------ | | `error` | `any` | -| `type?` | `ErrorTypes` \| [`NavigationFailureType`](enums/NavigationFailureType.md) | +| `type?` | [`ErrorTypes`](enums/ErrorTypes.md) \| [`NavigationFailureType`](enums/NavigationFailureType.md) | #### Returns @@ -318,7 +845,7 @@ ___ ### loadRouteLocation -▸ **loadRouteLocation**(`route`): `Promise`\<[`RouteLocationNormalizedLoaded`](interfaces/RouteLocationNormalizedLoaded.md)\> +▸ **loadRouteLocation**(`route`): `Promise`\<[`RouteLocationNormalizedLoaded`](index.md#RouteLocationNormalizedLoaded)\> Ensures a route is loaded, so it can be passed as o prop to ``. @@ -326,11 +853,11 @@ Ensures a route is loaded, so it can be passed as o prop to ``. | Name | Type | Description | | :------ | :------ | :------ | -| `route` | [`RouteLocationNormalized`](interfaces/RouteLocationNormalized.md) | resolved route to load | +| `route` | [`RouteLocationNormalizedGeneric`](interfaces/RouteLocationNormalizedGeneric.md) \| [`RouteLocationGeneric`](interfaces/RouteLocationGeneric.md) | resolved route to load | #### Returns -`Promise`\<[`RouteLocationNormalizedLoaded`](interfaces/RouteLocationNormalizedLoaded.md)\> +`Promise`\<[`RouteLocationNormalizedLoaded`](index.md#RouteLocationNormalizedLoaded)\> ___ @@ -374,40 +901,94 @@ component. The guard is removed when the component is unmounted. ___ -### useLink +### parseQuery + +▸ **parseQuery**(`search`): [`LocationQuery`](index.md#LocationQuery) -▸ **useLink**(`props`): `Object` +Transforms a queryString into a [LocationQuery](index.md#LocationQuery) object. Accept both, a +version with the leading `?` and without Should work as URLSearchParams #### Parameters -| Name | Type | -| :------ | :------ | -| `props` | `VueUseOptions`\<`RouterLinkOptions`\> | +| Name | Type | Description | +| :------ | :------ | :------ | +| `search` | `string` | search string to parse | #### Returns -`Object` +[`LocationQuery`](index.md#LocationQuery) + +a query object + +___ + +### stringifyQuery + +▸ **stringifyQuery**(`query`): `string` + +Stringifies a [LocationQueryRaw](index.md#LocationQueryRaw) object. Like `URLSearchParams`, it +doesn't prepend a `?` + +#### Parameters + +| Name | Type | Description | +| :------ | :------ | :------ | +| `query` | [`LocationQueryRaw`](index.md#LocationQueryRaw) | query object to stringify | + +#### Returns + +`string` + +string version of the query without the leading `?` + +___ + +### useLink + +▸ **useLink**\<`Name`\>(`props`): [`UseLinkReturn`](interfaces/UseLinkReturn.md)\<`Name`\> + +Returns the internal behavior of a [RouterLink](index.md#RouterLink) without the rendering part. + +#### Type parameters | Name | Type | | :------ | :------ | -| `href` | `ComputedRef`\<`string`\> | -| `isActive` | `ComputedRef`\<`boolean`\> | -| `isExactActive` | `ComputedRef`\<`boolean`\> | -| `navigate` | (`e`: `MouseEvent`) => `Promise`\<`void` \| [`NavigationFailure`](interfaces/NavigationFailure.md)\> | -| `route` | `ComputedRef`\<[`RouteLocation`](interfaces/RouteLocation.md) & \{ `href`: `string` }\> | +| `Name` | extends `string` \| `symbol` = `string` \| `symbol` | + +#### Parameters + +| Name | Type | Description | +| :------ | :------ | :------ | +| `props` | [`UseLinkOptions`](interfaces/UseLinkOptions.md)\<`Name`\> | a `to` location and an optional `replace` flag | + +#### Returns + +[`UseLinkReturn`](interfaces/UseLinkReturn.md)\<`Name`\> ___ ### useRoute -▸ **useRoute**(): [`RouteLocationNormalizedLoaded`](interfaces/RouteLocationNormalizedLoaded.md) +▸ **useRoute**\<`Name`\>(`_name?`): [`RouteLocationNormalizedLoaded`](index.md#RouteLocationNormalizedLoaded)\<`Name`\> Returns the current route location. Equivalent to using `$route` inside templates. +#### Type parameters + +| Name | Type | +| :------ | :------ | +| `Name` | extends `string` \| `symbol` = `string` \| `symbol` | + +#### Parameters + +| Name | Type | +| :------ | :------ | +| `_name?` | `Name` | + #### Returns -[`RouteLocationNormalizedLoaded`](interfaces/RouteLocationNormalizedLoaded.md) +[`RouteLocationNormalizedLoaded`](index.md#RouteLocationNormalizedLoaded)\<`Name`\> ___ diff --git a/packages/docs/api/interfaces/LocationAsRelativeRaw.md b/packages/docs/api/interfaces/LocationAsRelativeRaw.md new file mode 100644 index 000000000..41bdde049 --- /dev/null +++ b/packages/docs/api/interfaces/LocationAsRelativeRaw.md @@ -0,0 +1,33 @@ +--- +editLink: false +--- + +[API Documentation](../index.md) / LocationAsRelativeRaw + +# Interface: LocationAsRelativeRaw + +## Hierarchy + +- **`LocationAsRelativeRaw`** + + ↳ [`RouteLocationNamedRaw`](RouteLocationNamedRaw.md) + +## Properties + +### name + +• `Optional` **name**: [`RouteRecordNameGeneric`](../index.md#RouteRecordNameGeneric) + +___ + +### params + +• `Optional` **params**: [`RouteParamsRawGeneric`](../index.md#RouteParamsRawGeneric) + +___ + +### path + +• `Optional` **path**: `undefined` + +Ignored path property since we are dealing with a relative location. Only `undefined` is allowed. diff --git a/packages/docs/api/interfaces/MatcherLocation.md b/packages/docs/api/interfaces/MatcherLocation.md new file mode 100644 index 000000000..6e6ed70aa --- /dev/null +++ b/packages/docs/api/interfaces/MatcherLocation.md @@ -0,0 +1,51 @@ +--- +editLink: false +--- + +[API Documentation](../index.md) / MatcherLocation + +# Interface: MatcherLocation + +Normalized/resolved Route location that returned by the matcher. + +## Properties + +### matched + +• **matched**: [`RouteRecordNormalized`](RouteRecordNormalized.md)[] + +Array of [RouteRecord](../index.md#RouteRecord) containing components as they were +passed when adding records. It can also contain redirect records. This +can't be used directly + +___ + +### meta + +• **meta**: [`RouteMeta`](RouteMeta.md) + +Merged `meta` properties from all the matched route records. + +___ + +### name + +• **name**: ``null`` \| [`RouteRecordNameGeneric`](../index.md#RouteRecordNameGeneric) + +Name of the matched record + +___ + +### params + +• **params**: [`RouteParamsGeneric`](../index.md#RouteParamsGeneric) + +Object of decoded params extracted from the `path`. + +___ + +### path + +• **path**: `string` + +Percentage encoded pathname section of the URL. diff --git a/packages/docs/api/interfaces/MatcherLocationAsPath.md b/packages/docs/api/interfaces/MatcherLocationAsPath.md new file mode 100644 index 000000000..f2a039c2b --- /dev/null +++ b/packages/docs/api/interfaces/MatcherLocationAsPath.md @@ -0,0 +1,19 @@ +--- +editLink: false +--- + +[API Documentation](../index.md) / MatcherLocationAsPath + +# Interface: MatcherLocationAsPath + +## Hierarchy + +- **`MatcherLocationAsPath`** + + ↳ [`RouteLocationPathRaw`](RouteLocationPathRaw.md) + +## Properties + +### path + +• **path**: `string` diff --git a/packages/docs/api/interfaces/NavigationFailure.md b/packages/docs/api/interfaces/NavigationFailure.md index c9e80423a..2c15e371c 100644 --- a/packages/docs/api/interfaces/NavigationFailure.md +++ b/packages/docs/api/interfaces/NavigationFailure.md @@ -28,7 +28,7 @@ ___ ### from -• **from**: [`RouteLocationNormalized`](RouteLocationNormalized.md) +• **from**: [`RouteLocationNormalizedGeneric`](RouteLocationNormalizedGeneric.md) Route location we were navigating from @@ -66,7 +66,7 @@ ___ ### to -• **to**: [`RouteLocationNormalized`](RouteLocationNormalized.md) +• **to**: [`RouteLocationNormalizedGeneric`](RouteLocationNormalizedGeneric.md) Route location we were navigating to @@ -74,6 +74,6 @@ ___ ### type -• **type**: `NAVIGATION_ABORTED` \| `NAVIGATION_CANCELLED` \| `NAVIGATION_DUPLICATED` +• **type**: [`NAVIGATION_ABORTED`](../enums/ErrorTypes.md#NAVIGATION_ABORTED) \| [`NAVIGATION_CANCELLED`](../enums/ErrorTypes.md#NAVIGATION_CANCELLED) \| [`NAVIGATION_DUPLICATED`](../enums/ErrorTypes.md#NAVIGATION_DUPLICATED) Type of the navigation. One of [NavigationFailureType](../enums/NavigationFailureType.md) diff --git a/packages/docs/api/interfaces/NavigationGuard.md b/packages/docs/api/interfaces/NavigationGuard.md index 7a9a4865c..9a769972f 100644 --- a/packages/docs/api/interfaces/NavigationGuard.md +++ b/packages/docs/api/interfaces/NavigationGuard.md @@ -6,23 +6,22 @@ editLink: false # Interface: NavigationGuard -Navigation guard. See [Navigation -Guards](/guide/advanced/navigation-guards.md). +Navigation Guard. ## Callable ### NavigationGuard -▸ **NavigationGuard**(`to`, `from`, `next`): `NavigationGuardReturn` \| `Promise`\<`NavigationGuardReturn`\> +▸ **NavigationGuard**(`to`, `from`, `next`): [`_Awaitable`](../index.md#_Awaitable)\<[`NavigationGuardReturn`](../index.md#NavigationGuardReturn)\> #### Parameters | Name | Type | | :------ | :------ | -| `to` | [`RouteLocationNormalized`](RouteLocationNormalized.md) | -| `from` | [`RouteLocationNormalized`](RouteLocationNormalized.md) | +| `to` | [`RouteLocationNormalizedGeneric`](RouteLocationNormalizedGeneric.md) | +| `from` | [`RouteLocationNormalizedLoadedGeneric`](RouteLocationNormalizedLoadedGeneric.md) | | `next` | [`NavigationGuardNext`](NavigationGuardNext.md) | #### Returns -`NavigationGuardReturn` \| `Promise`\<`NavigationGuardReturn`\> +[`_Awaitable`](../index.md#_Awaitable)\<[`NavigationGuardReturn`](../index.md#NavigationGuardReturn)\> diff --git a/packages/docs/api/interfaces/NavigationGuardNext.md b/packages/docs/api/interfaces/NavigationGuardNext.md index b736b12d6..6e45e228b 100644 --- a/packages/docs/api/interfaces/NavigationGuardNext.md +++ b/packages/docs/api/interfaces/NavigationGuardNext.md @@ -6,6 +6,8 @@ editLink: false # Interface: NavigationGuardNext +`next()` callback passed to navigation guards. + ## Callable ### NavigationGuardNext @@ -38,7 +40,7 @@ editLink: false | Name | Type | | :------ | :------ | -| `location` | [`RouteLocationRaw`](../index.md#RouteLocationRaw) | +| `location` | `string` \| [`RouteLocationAsRelativeGeneric`](RouteLocationAsRelativeGeneric.md) \| [`RouteLocationAsPathGeneric`](RouteLocationAsPathGeneric.md) | #### Returns @@ -66,7 +68,7 @@ editLink: false | Name | Type | | :------ | :------ | -| `cb` | `NavigationGuardNextCallback` | +| `cb` | [`NavigationGuardNextCallback`](../index.md#NavigationGuardNextCallback) | #### Returns diff --git a/packages/docs/api/interfaces/NavigationGuardWithThis.md b/packages/docs/api/interfaces/NavigationGuardWithThis.md index 4b4fae7b0..9c527cc60 100644 --- a/packages/docs/api/interfaces/NavigationGuardWithThis.md +++ b/packages/docs/api/interfaces/NavigationGuardWithThis.md @@ -6,8 +6,11 @@ editLink: false # Interface: NavigationGuardWithThis\ -Navigation guard. See [Navigation -Guards](/guide/advanced/navigation-guards.md). +Navigation Guard with a type parameter for `this`. + +**`See`** + +[TypesConfig](TypesConfig.md) ## Type parameters @@ -19,17 +22,17 @@ Guards](/guide/advanced/navigation-guards.md). ### NavigationGuardWithThis -▸ **NavigationGuardWithThis**(`this`, `to`, `from`, `next`): `NavigationGuardReturn` \| `Promise`\<`NavigationGuardReturn`\> +▸ **NavigationGuardWithThis**(`this`, `to`, `from`, `next`): [`_Awaitable`](../index.md#_Awaitable)\<[`NavigationGuardReturn`](../index.md#NavigationGuardReturn)\> #### Parameters | Name | Type | | :------ | :------ | | `this` | `T` | -| `to` | [`RouteLocationNormalized`](RouteLocationNormalized.md) | -| `from` | [`RouteLocationNormalized`](RouteLocationNormalized.md) | +| `to` | [`RouteLocationNormalizedGeneric`](RouteLocationNormalizedGeneric.md) | +| `from` | [`RouteLocationNormalizedLoadedGeneric`](RouteLocationNormalizedLoadedGeneric.md) | | `next` | [`NavigationGuardNext`](NavigationGuardNext.md) | #### Returns -`NavigationGuardReturn` \| `Promise`\<`NavigationGuardReturn`\> +[`_Awaitable`](../index.md#_Awaitable)\<[`NavigationGuardReturn`](../index.md#NavigationGuardReturn)\> diff --git a/packages/docs/api/interfaces/NavigationHookAfter.md b/packages/docs/api/interfaces/NavigationHookAfter.md index 309d11311..a797b51eb 100644 --- a/packages/docs/api/interfaces/NavigationHookAfter.md +++ b/packages/docs/api/interfaces/NavigationHookAfter.md @@ -6,20 +6,22 @@ editLink: false # Interface: NavigationHookAfter +Navigation hook triggered after a navigation is settled. + ## Callable ### NavigationHookAfter -▸ **NavigationHookAfter**(`to`, `from`, `failure?`): `any` +▸ **NavigationHookAfter**(`to`, `from`, `failure?`): `unknown` #### Parameters | Name | Type | | :------ | :------ | -| `to` | [`RouteLocationNormalized`](RouteLocationNormalized.md) | -| `from` | [`RouteLocationNormalized`](RouteLocationNormalized.md) | +| `to` | [`RouteLocationNormalizedGeneric`](RouteLocationNormalizedGeneric.md) | +| `from` | [`RouteLocationNormalizedLoadedGeneric`](RouteLocationNormalizedLoadedGeneric.md) | | `failure?` | `void` \| [`NavigationFailure`](NavigationFailure.md) | #### Returns -`any` +`unknown` diff --git a/packages/docs/api/interfaces/NavigationRedirectError.md b/packages/docs/api/interfaces/NavigationRedirectError.md new file mode 100644 index 000000000..b0403d3b9 --- /dev/null +++ b/packages/docs/api/interfaces/NavigationRedirectError.md @@ -0,0 +1,79 @@ +--- +editLink: false +--- + +[API Documentation](../index.md) / NavigationRedirectError + +# Interface: NavigationRedirectError + +Internal error used to detect a redirection. + +## Hierarchy + +- `Omit`\<[`NavigationFailure`](NavigationFailure.md), ``"to"`` \| ``"type"``\> + + ↳ **`NavigationRedirectError`** + +## Properties + +### cause + +• `Optional` **cause**: `unknown` + +#### Inherited from + +Omit.cause + +___ + +### from + +• **from**: [`RouteLocationNormalizedGeneric`](RouteLocationNormalizedGeneric.md) + +Route location we were navigating from + +#### Inherited from + +Omit.from + +___ + +### message + +• **message**: `string` + +#### Inherited from + +Omit.message + +___ + +### name + +• **name**: `string` + +#### Inherited from + +Omit.name + +___ + +### stack + +• `Optional` **stack**: `string` + +#### Inherited from + +Omit.stack + +___ + +### to + +• **to**: `string` \| [`RouteLocationAsRelativeGeneric`](RouteLocationAsRelativeGeneric.md) \| [`RouteLocationAsPathGeneric`](RouteLocationAsPathGeneric.md) + +___ + +### type + +• **type**: [`NAVIGATION_GUARD_REDIRECT`](../enums/ErrorTypes.md#NAVIGATION_GUARD_REDIRECT) diff --git a/packages/docs/api/interfaces/PathParserOptions.md b/packages/docs/api/interfaces/PathParserOptions.md new file mode 100644 index 000000000..51c2563e5 --- /dev/null +++ b/packages/docs/api/interfaces/PathParserOptions.md @@ -0,0 +1,55 @@ +--- +editLink: false +--- + +[API Documentation](../index.md) / \_PathParserOptions + +# Interface: \_PathParserOptions + +## Properties + +### end + +• `Optional` **end**: `boolean` + +Should the RegExp match until the end by appending a `$` to it. + +**`Default Value`** + +`true` + +___ + +### sensitive + +• `Optional` **sensitive**: `boolean` + +Makes the RegExp case-sensitive. + +**`Default Value`** + +`false` + +___ + +### start + +• `Optional` **start**: `boolean` + +Should the RegExp match from the beginning by prepending a `^` to it. + +**`Default Value`** + +`true` + +___ + +### strict + +• `Optional` **strict**: `boolean` + +Whether to disallow a trailing slash or not. + +**`Default Value`** + +`false` diff --git a/packages/docs/api/interfaces/RouteLocation.md b/packages/docs/api/interfaces/RouteLocation.md deleted file mode 100644 index 0aa1986ec..000000000 --- a/packages/docs/api/interfaces/RouteLocation.md +++ /dev/null @@ -1,123 +0,0 @@ ---- -editLink: false ---- - -[API Documentation](../index.md) / RouteLocation - -# Interface: RouteLocation - -[RouteLocationRaw](../index.md#RouteLocationRaw) resolved using the matcher - -## Hierarchy - -- `_RouteLocationBase` - - ↳ **`RouteLocation`** - -## Properties - -### fullPath - -• **fullPath**: `string` - -The whole location including the `search` and `hash`. This string is -percentage encoded. - -#### Inherited from - -\_RouteLocationBase.fullPath - -___ - -### hash - -• **hash**: `string` - -Hash of the current location. If present, starts with a `#`. - -#### Inherited from - -\_RouteLocationBase.hash - -___ - -### matched - -• **matched**: [`RouteRecordNormalized`](RouteRecordNormalized.md)[] - -Array of [RouteRecord](../index.md#RouteRecord) containing components as they were -passed when adding records. It can also contain redirect records. This -can't be used directly - -___ - -### meta - -• **meta**: [`RouteMeta`](RouteMeta.md) - -Merged `meta` properties from all the matched route records. - -#### Inherited from - -\_RouteLocationBase.meta - -___ - -### name - -• **name**: `undefined` \| ``null`` \| [`RouteRecordName`](../index.md#RouteRecordName) - -Name of the matched record - -#### Inherited from - -\_RouteLocationBase.name - -___ - -### params - -• **params**: [`RouteParams`](../index.md#RouteParams) - -Object of decoded params extracted from the `path`. - -#### Inherited from - -\_RouteLocationBase.params - -___ - -### path - -• **path**: `string` - -Percentage encoded pathname section of the URL. - -#### Inherited from - -\_RouteLocationBase.path - -___ - -### query - -• **query**: [`LocationQuery`](../index.md#LocationQuery) - -Object representation of the `search` property of the current location. - -#### Inherited from - -\_RouteLocationBase.query - -___ - -### redirectedFrom - -• **redirectedFrom**: `undefined` \| [`RouteLocation`](RouteLocation.md) - -Contains the location we were initially trying to access before ending up -on the current location. - -#### Inherited from - -\_RouteLocationBase.redirectedFrom diff --git a/packages/docs/api/interfaces/RouteLocationAsPathGeneric.md b/packages/docs/api/interfaces/RouteLocationAsPathGeneric.md new file mode 100644 index 000000000..8e7980386 --- /dev/null +++ b/packages/docs/api/interfaces/RouteLocationAsPathGeneric.md @@ -0,0 +1,87 @@ +--- +editLink: false +--- + +[API Documentation](../index.md) / RouteLocationAsPathGeneric + +# Interface: RouteLocationAsPathGeneric + +Generic version of [RouteLocationAsPath](../index.md#RouteLocationAsPath). It is used when no [RouteMap](../index.md#RouteMap) is provided. + +## Hierarchy + +- [`RouteQueryAndHash`](RouteQueryAndHash.md) + +- [`RouteLocationOptions`](RouteLocationOptions.md) + + ↳ **`RouteLocationAsPathGeneric`** + + ↳↳ [`RouteLocationAsPathTyped`](RouteLocationAsPathTyped.md) + +## Properties + +### force + +• `Optional` **force**: `boolean` + +Triggers the navigation even if the location is the same as the current one. +Note this will also add a new entry to the history unless `replace: true` +is passed. + +#### Inherited from + +[RouteLocationOptions](RouteLocationOptions.md).[force](RouteLocationOptions.md#force) + +___ + +### hash + +• `Optional` **hash**: `string` + +#### Inherited from + +[RouteQueryAndHash](RouteQueryAndHash.md).[hash](RouteQueryAndHash.md#hash) + +___ + +### path + +• **path**: `string` + +Percentage encoded pathname section of the URL. + +___ + +### query + +• `Optional` **query**: [`LocationQueryRaw`](../index.md#LocationQueryRaw) + +#### Inherited from + +[RouteQueryAndHash](RouteQueryAndHash.md).[query](RouteQueryAndHash.md#query) + +___ + +### replace + +• `Optional` **replace**: `boolean` + +Replace the entry in the history instead of pushing a new entry + +#### Inherited from + +[RouteLocationOptions](RouteLocationOptions.md).[replace](RouteLocationOptions.md#replace) + +___ + +### state + +• `Optional` **state**: [`HistoryState`](HistoryState.md) + +State to save using the History API. This cannot contain any reactive +values and some primitives like Symbols are forbidden. More info at +https://developer.mozilla.org/en-US/docs/Web/API/History/state + +#### Inherited from + +[RouteLocationOptions](RouteLocationOptions.md).[state](RouteLocationOptions.md#state) diff --git a/packages/docs/api/interfaces/RouteLocationAsPathTyped.md b/packages/docs/api/interfaces/RouteLocationAsPathTyped.md new file mode 100644 index 000000000..17b81286e --- /dev/null +++ b/packages/docs/api/interfaces/RouteLocationAsPathTyped.md @@ -0,0 +1,94 @@ +--- +editLink: false +--- + +[API Documentation](../index.md) / RouteLocationAsPathTyped + +# Interface: RouteLocationAsPathTyped\ + +Helper to generate a type safe version of the [RouteLocationAsPath](../index.md#RouteLocationAsPath) type. + +## Type parameters + +| Name | Type | +| :------ | :------ | +| `RouteMap` | extends [`RouteMapGeneric`](../index.md#RouteMapGeneric) = [`RouteMapGeneric`](../index.md#RouteMapGeneric) | +| `Name` | extends keyof `RouteMap` = keyof `RouteMap` | + +## Hierarchy + +- [`RouteLocationAsPathGeneric`](RouteLocationAsPathGeneric.md) + + ↳ **`RouteLocationAsPathTyped`** + +## Properties + +### force + +• `Optional` **force**: `boolean` + +Triggers the navigation even if the location is the same as the current one. +Note this will also add a new entry to the history unless `replace: true` +is passed. + +#### Inherited from + +[RouteLocationAsPathGeneric](RouteLocationAsPathGeneric.md).[force](RouteLocationAsPathGeneric.md#force) + +___ + +### hash + +• `Optional` **hash**: `string` + +#### Inherited from + +[RouteLocationAsPathGeneric](RouteLocationAsPathGeneric.md).[hash](RouteLocationAsPathGeneric.md#hash) + +___ + +### path + +• **path**: `_LiteralUnion`\<`RouteMap`[`Name`][``"path"``]\> + +Percentage encoded pathname section of the URL. + +#### Overrides + +[RouteLocationAsPathGeneric](RouteLocationAsPathGeneric.md).[path](RouteLocationAsPathGeneric.md#path) + +___ + +### query + +• `Optional` **query**: [`LocationQueryRaw`](../index.md#LocationQueryRaw) + +#### Inherited from + +[RouteLocationAsPathGeneric](RouteLocationAsPathGeneric.md).[query](RouteLocationAsPathGeneric.md#query) + +___ + +### replace + +• `Optional` **replace**: `boolean` + +Replace the entry in the history instead of pushing a new entry + +#### Inherited from + +[RouteLocationAsPathGeneric](RouteLocationAsPathGeneric.md).[replace](RouteLocationAsPathGeneric.md#replace) + +___ + +### state + +• `Optional` **state**: [`HistoryState`](HistoryState.md) + +State to save using the History API. This cannot contain any reactive +values and some primitives like Symbols are forbidden. More info at +https://developer.mozilla.org/en-US/docs/Web/API/History/state + +#### Inherited from + +[RouteLocationAsPathGeneric](RouteLocationAsPathGeneric.md).[state](RouteLocationAsPathGeneric.md#state) diff --git a/packages/docs/api/interfaces/RouteLocationAsRelativeGeneric.md b/packages/docs/api/interfaces/RouteLocationAsRelativeGeneric.md new file mode 100644 index 000000000..e413c72f0 --- /dev/null +++ b/packages/docs/api/interfaces/RouteLocationAsRelativeGeneric.md @@ -0,0 +1,99 @@ +--- +editLink: false +--- + +[API Documentation](../index.md) / RouteLocationAsRelativeGeneric + +# Interface: RouteLocationAsRelativeGeneric + +Generic version of [RouteLocationAsRelative](../index.md#RouteLocationAsRelative). It is used when no [RouteMap](../index.md#RouteMap) is provided. + +## Hierarchy + +- [`RouteQueryAndHash`](RouteQueryAndHash.md) + +- [`RouteLocationOptions`](RouteLocationOptions.md) + + ↳ **`RouteLocationAsRelativeGeneric`** + + ↳↳ [`RouteLocationAsRelativeTyped`](RouteLocationAsRelativeTyped.md) + +## Properties + +### force + +• `Optional` **force**: `boolean` + +Triggers the navigation even if the location is the same as the current one. +Note this will also add a new entry to the history unless `replace: true` +is passed. + +#### Inherited from + +[RouteLocationOptions](RouteLocationOptions.md).[force](RouteLocationOptions.md#force) + +___ + +### hash + +• `Optional` **hash**: `string` + +#### Inherited from + +[RouteQueryAndHash](RouteQueryAndHash.md).[hash](RouteQueryAndHash.md#hash) + +___ + +### name + +• `Optional` **name**: [`RouteRecordNameGeneric`](../index.md#RouteRecordNameGeneric) + +___ + +### params + +• `Optional` **params**: [`RouteParamsRawGeneric`](../index.md#RouteParamsRawGeneric) + +___ + +### path + +• `Optional` **path**: `undefined` + +A relative path to the current location. This property should be removed + +___ + +### query + +• `Optional` **query**: [`LocationQueryRaw`](../index.md#LocationQueryRaw) + +#### Inherited from + +[RouteQueryAndHash](RouteQueryAndHash.md).[query](RouteQueryAndHash.md#query) + +___ + +### replace + +• `Optional` **replace**: `boolean` + +Replace the entry in the history instead of pushing a new entry + +#### Inherited from + +[RouteLocationOptions](RouteLocationOptions.md).[replace](RouteLocationOptions.md#replace) + +___ + +### state + +• `Optional` **state**: [`HistoryState`](HistoryState.md) + +State to save using the History API. This cannot contain any reactive +values and some primitives like Symbols are forbidden. More info at +https://developer.mozilla.org/en-US/docs/Web/API/History/state + +#### Inherited from + +[RouteLocationOptions](RouteLocationOptions.md).[state](RouteLocationOptions.md#state) diff --git a/packages/docs/api/interfaces/RouteLocationAsRelativeTyped.md b/packages/docs/api/interfaces/RouteLocationAsRelativeTyped.md new file mode 100644 index 000000000..05078fe8b --- /dev/null +++ b/packages/docs/api/interfaces/RouteLocationAsRelativeTyped.md @@ -0,0 +1,114 @@ +--- +editLink: false +--- + +[API Documentation](../index.md) / RouteLocationAsRelativeTyped + +# Interface: RouteLocationAsRelativeTyped\ + +Helper to generate a type safe version of the [RouteLocationAsRelative](../index.md#RouteLocationAsRelative) type. + +## Type parameters + +| Name | Type | +| :------ | :------ | +| `RouteMap` | extends [`RouteMapGeneric`](../index.md#RouteMapGeneric) = [`RouteMapGeneric`](../index.md#RouteMapGeneric) | +| `Name` | extends keyof `RouteMap` = keyof `RouteMap` | + +## Hierarchy + +- [`RouteLocationAsRelativeGeneric`](RouteLocationAsRelativeGeneric.md) + + ↳ **`RouteLocationAsRelativeTyped`** + +## Properties + +### force + +• `Optional` **force**: `boolean` + +Triggers the navigation even if the location is the same as the current one. +Note this will also add a new entry to the history unless `replace: true` +is passed. + +#### Inherited from + +[RouteLocationAsRelativeGeneric](RouteLocationAsRelativeGeneric.md).[force](RouteLocationAsRelativeGeneric.md#force) + +___ + +### hash + +• `Optional` **hash**: `string` + +#### Inherited from + +[RouteLocationAsRelativeGeneric](RouteLocationAsRelativeGeneric.md).[hash](RouteLocationAsRelativeGeneric.md#hash) + +___ + +### name + +• `Optional` **name**: `Extract`\<`Name`, `string` \| `symbol`\> + +#### Overrides + +[RouteLocationAsRelativeGeneric](RouteLocationAsRelativeGeneric.md).[name](RouteLocationAsRelativeGeneric.md#name) + +___ + +### params + +• `Optional` **params**: `RouteMap`[`Name`][``"paramsRaw"``] + +#### Overrides + +[RouteLocationAsRelativeGeneric](RouteLocationAsRelativeGeneric.md).[params](RouteLocationAsRelativeGeneric.md#params) + +___ + +### path + +• `Optional` **path**: `undefined` + +A relative path to the current location. This property should be removed + +#### Inherited from + +[RouteLocationAsRelativeGeneric](RouteLocationAsRelativeGeneric.md).[path](RouteLocationAsRelativeGeneric.md#path) + +___ + +### query + +• `Optional` **query**: [`LocationQueryRaw`](../index.md#LocationQueryRaw) + +#### Inherited from + +[RouteLocationAsRelativeGeneric](RouteLocationAsRelativeGeneric.md).[query](RouteLocationAsRelativeGeneric.md#query) + +___ + +### replace + +• `Optional` **replace**: `boolean` + +Replace the entry in the history instead of pushing a new entry + +#### Inherited from + +[RouteLocationAsRelativeGeneric](RouteLocationAsRelativeGeneric.md).[replace](RouteLocationAsRelativeGeneric.md#replace) + +___ + +### state + +• `Optional` **state**: [`HistoryState`](HistoryState.md) + +State to save using the History API. This cannot contain any reactive +values and some primitives like Symbols are forbidden. More info at +https://developer.mozilla.org/en-US/docs/Web/API/History/state + +#### Inherited from + +[RouteLocationAsRelativeGeneric](RouteLocationAsRelativeGeneric.md).[state](RouteLocationAsRelativeGeneric.md#state) diff --git a/packages/docs/api/interfaces/RouteLocationBase.md b/packages/docs/api/interfaces/RouteLocationBase.md new file mode 100644 index 000000000..b26cfe81a --- /dev/null +++ b/packages/docs/api/interfaces/RouteLocationBase.md @@ -0,0 +1,101 @@ +--- +editLink: false +--- + +[API Documentation](../index.md) / \_RouteLocationBase + +# Interface: \_RouteLocationBase + +Base properties for a normalized route location. + +## Hierarchy + +- `Pick`\<[`MatcherLocation`](MatcherLocation.md), ``"name"`` \| ``"path"`` \| ``"params"`` \| ``"meta"``\> + + ↳ **`_RouteLocationBase`** + + ↳↳ [`RouteLocationGeneric`](RouteLocationGeneric.md) + + ↳↳ [`RouteLocationNormalizedGeneric`](RouteLocationNormalizedGeneric.md) + +## Properties + +### fullPath + +• **fullPath**: `string` + +The whole location including the `search` and `hash`. This string is +percentage encoded. + +___ + +### hash + +• **hash**: `string` + +Hash of the current location. If present, starts with a `#`. + +___ + +### meta + +• **meta**: [`RouteMeta`](RouteMeta.md) + +Merged `meta` properties from all the matched route records. + +#### Inherited from + +Pick.meta + +___ + +### name + +• **name**: ``null`` \| [`RouteRecordNameGeneric`](../index.md#RouteRecordNameGeneric) + +Name of the matched record + +#### Inherited from + +Pick.name + +___ + +### params + +• **params**: [`RouteParamsGeneric`](../index.md#RouteParamsGeneric) + +Object of decoded params extracted from the `path`. + +#### Inherited from + +Pick.params + +___ + +### path + +• **path**: `string` + +Percentage encoded pathname section of the URL. + +#### Inherited from + +Pick.path + +___ + +### query + +• **query**: [`LocationQuery`](../index.md#LocationQuery) + +Object representation of the `search` property of the current location. + +___ + +### redirectedFrom + +• **redirectedFrom**: `undefined` \| [`RouteLocationGeneric`](RouteLocationGeneric.md) + +Contains the location we were initially trying to access before ending up +on the current location. diff --git a/packages/docs/api/interfaces/RouteLocationGeneric.md b/packages/docs/api/interfaces/RouteLocationGeneric.md new file mode 100644 index 000000000..534be974a --- /dev/null +++ b/packages/docs/api/interfaces/RouteLocationGeneric.md @@ -0,0 +1,127 @@ +--- +editLink: false +--- + +[API Documentation](../index.md) / RouteLocationGeneric + +# Interface: RouteLocationGeneric + +Generic version of [RouteLocation](../index.md#RouteLocation). It is used when no [RouteMap](../index.md#RouteMap) is provided. + +## Hierarchy + +- [`_RouteLocationBase`](RouteLocationBase.md) + + ↳ **`RouteLocationGeneric`** + + ↳↳ [`RouteLocationTyped`](RouteLocationTyped.md) + + ↳↳ [`RouteLocationResolvedGeneric`](RouteLocationResolvedGeneric.md) + +## Properties + +### fullPath + +• **fullPath**: `string` + +The whole location including the `search` and `hash`. This string is +percentage encoded. + +#### Inherited from + +[_RouteLocationBase](RouteLocationBase.md).[fullPath](RouteLocationBase.md#fullPath) + +___ + +### hash + +• **hash**: `string` + +Hash of the current location. If present, starts with a `#`. + +#### Inherited from + +[_RouteLocationBase](RouteLocationBase.md).[hash](RouteLocationBase.md#hash) + +___ + +### matched + +• **matched**: [`RouteRecordNormalized`](RouteRecordNormalized.md)[] + +Array of [RouteRecord](../index.md#RouteRecord) containing components as they were +passed when adding records. It can also contain redirect records. This +can't be used directly. **This property is non-enumerable**. + +___ + +### meta + +• **meta**: [`RouteMeta`](RouteMeta.md) + +Merged `meta` properties from all the matched route records. + +#### Inherited from + +[_RouteLocationBase](RouteLocationBase.md).[meta](RouteLocationBase.md#meta) + +___ + +### name + +• **name**: ``null`` \| [`RouteRecordNameGeneric`](../index.md#RouteRecordNameGeneric) + +Name of the matched record + +#### Inherited from + +[_RouteLocationBase](RouteLocationBase.md).[name](RouteLocationBase.md#name) + +___ + +### params + +• **params**: [`RouteParamsGeneric`](../index.md#RouteParamsGeneric) + +Object of decoded params extracted from the `path`. + +#### Inherited from + +[_RouteLocationBase](RouteLocationBase.md).[params](RouteLocationBase.md#params) + +___ + +### path + +• **path**: `string` + +Percentage encoded pathname section of the URL. + +#### Inherited from + +[_RouteLocationBase](RouteLocationBase.md).[path](RouteLocationBase.md#path) + +___ + +### query + +• **query**: [`LocationQuery`](../index.md#LocationQuery) + +Object representation of the `search` property of the current location. + +#### Inherited from + +[_RouteLocationBase](RouteLocationBase.md).[query](RouteLocationBase.md#query) + +___ + +### redirectedFrom + +• **redirectedFrom**: `undefined` \| [`RouteLocationGeneric`](RouteLocationGeneric.md) + +Contains the location we were initially trying to access before ending up +on the current location. + +#### Inherited from + +[_RouteLocationBase](RouteLocationBase.md).[redirectedFrom](RouteLocationBase.md#redirectedFrom) diff --git a/packages/docs/api/interfaces/RouteLocationMatched.md b/packages/docs/api/interfaces/RouteLocationMatched.md index cf649dd73..7bc60f858 100644 --- a/packages/docs/api/interfaces/RouteLocationMatched.md +++ b/packages/docs/api/interfaces/RouteLocationMatched.md @@ -65,6 +65,18 @@ Components to display when the URL matches this route. Allow using named views. ___ +### enterCallbacks + +• **enterCallbacks**: `Record`\<`string`, [`NavigationGuardNextCallback`](../index.md#NavigationGuardNextCallback)[]\> + +Registered beforeRouteEnter callbacks passed to `next` or returned in guards + +#### Inherited from + +[RouteRecordNormalized](RouteRecordNormalized.md).[enterCallbacks](RouteRecordNormalized.md#enterCallbacks) + +___ + ### instances • **instances**: `Record`\<`string`, `undefined` \| ``null`` \| `ComponentPublicInstance`\> @@ -83,6 +95,18 @@ views. ___ +### leaveGuards + +• **leaveGuards**: `Set`\<[`NavigationGuard`](NavigationGuard.md)\> + +Registered leave guards + +#### Inherited from + +[RouteRecordNormalized](RouteRecordNormalized.md).[leaveGuards](RouteRecordNormalized.md#leaveGuards) + +___ + ### meta • **meta**: [`RouteMeta`](RouteMeta.md) @@ -97,7 +121,7 @@ ___ ### name -• **name**: `undefined` \| [`RouteRecordName`](../index.md#RouteRecordName) +• **name**: [`RouteRecordNameGeneric`](../index.md#RouteRecordNameGeneric) Name for the route record. Must be unique. @@ -122,7 +146,7 @@ ___ ### props -• **props**: `Record`\<`string`, `_RouteRecordProps`\> +• **props**: `Record`\<`string`, [`_RouteRecordProps`](../index.md#_RouteRecordProps)\> Allow passing down params as props to the component rendered by `router-view`. Should be an object with the same keys as `components` or a @@ -136,7 +160,7 @@ ___ ### redirect -• **redirect**: `undefined` \| `RouteRecordRedirectOption` +• **redirect**: `undefined` \| [`RouteRecordRedirectOption`](../index.md#RouteRecordRedirectOption) Where to redirect if the route is directly matched. The redirection happens before any navigation guard and triggers a new navigation with the new @@ -145,3 +169,15 @@ target location. #### Inherited from [RouteRecordNormalized](RouteRecordNormalized.md).[redirect](RouteRecordNormalized.md#redirect) + +___ + +### updateGuards + +• **updateGuards**: `Set`\<[`NavigationGuard`](NavigationGuard.md)\> + +Registered update guards + +#### Inherited from + +[RouteRecordNormalized](RouteRecordNormalized.md).[updateGuards](RouteRecordNormalized.md#updateGuards) diff --git a/packages/docs/api/interfaces/RouteLocationNamedRaw.md b/packages/docs/api/interfaces/RouteLocationNamedRaw.md new file mode 100644 index 000000000..9883d02aa --- /dev/null +++ b/packages/docs/api/interfaces/RouteLocationNamedRaw.md @@ -0,0 +1,111 @@ +--- +editLink: false +--- + +[API Documentation](../index.md) / RouteLocationNamedRaw + +# Interface: RouteLocationNamedRaw + +Route Location that can infer the necessary params based on the name. + +## Hierarchy + +- [`RouteQueryAndHash`](RouteQueryAndHash.md) + +- [`LocationAsRelativeRaw`](LocationAsRelativeRaw.md) + +- [`RouteLocationOptions`](RouteLocationOptions.md) + + ↳ **`RouteLocationNamedRaw`** + +## Properties + +### force + +• `Optional` **force**: `boolean` + +Triggers the navigation even if the location is the same as the current one. +Note this will also add a new entry to the history unless `replace: true` +is passed. + +#### Inherited from + +[RouteLocationOptions](RouteLocationOptions.md).[force](RouteLocationOptions.md#force) + +___ + +### hash + +• `Optional` **hash**: `string` + +#### Inherited from + +[RouteQueryAndHash](RouteQueryAndHash.md).[hash](RouteQueryAndHash.md#hash) + +___ + +### name + +• `Optional` **name**: [`RouteRecordNameGeneric`](../index.md#RouteRecordNameGeneric) + +#### Inherited from + +[LocationAsRelativeRaw](LocationAsRelativeRaw.md).[name](LocationAsRelativeRaw.md#name) + +___ + +### params + +• `Optional` **params**: [`RouteParamsRawGeneric`](../index.md#RouteParamsRawGeneric) + +#### Inherited from + +[LocationAsRelativeRaw](LocationAsRelativeRaw.md).[params](LocationAsRelativeRaw.md#params) + +___ + +### path + +• `Optional` **path**: `undefined` + +Ignored path property since we are dealing with a relative location. Only `undefined` is allowed. + +#### Inherited from + +[LocationAsRelativeRaw](LocationAsRelativeRaw.md).[path](LocationAsRelativeRaw.md#path) + +___ + +### query + +• `Optional` **query**: [`LocationQueryRaw`](../index.md#LocationQueryRaw) + +#### Inherited from + +[RouteQueryAndHash](RouteQueryAndHash.md).[query](RouteQueryAndHash.md#query) + +___ + +### replace + +• `Optional` **replace**: `boolean` + +Replace the entry in the history instead of pushing a new entry + +#### Inherited from + +[RouteLocationOptions](RouteLocationOptions.md).[replace](RouteLocationOptions.md#replace) + +___ + +### state + +• `Optional` **state**: [`HistoryState`](HistoryState.md) + +State to save using the History API. This cannot contain any reactive +values and some primitives like Symbols are forbidden. More info at +https://developer.mozilla.org/en-US/docs/Web/API/History/state + +#### Inherited from + +[RouteLocationOptions](RouteLocationOptions.md).[state](RouteLocationOptions.md#state) diff --git a/packages/docs/api/interfaces/RouteLocationNormalized.md b/packages/docs/api/interfaces/RouteLocationNormalized.md deleted file mode 100644 index 43949a3bd..000000000 --- a/packages/docs/api/interfaces/RouteLocationNormalized.md +++ /dev/null @@ -1,122 +0,0 @@ ---- -editLink: false ---- - -[API Documentation](../index.md) / RouteLocationNormalized - -# Interface: RouteLocationNormalized - -Similar to [RouteLocation](RouteLocation.md) but its -[RouteLocationNormalized.matched](RouteLocationNormalized.md#matched) cannot contain redirect records - -## Hierarchy - -- `_RouteLocationBase` - - ↳ **`RouteLocationNormalized`** - -## Properties - -### fullPath - -• **fullPath**: `string` - -The whole location including the `search` and `hash`. This string is -percentage encoded. - -#### Inherited from - -\_RouteLocationBase.fullPath - -___ - -### hash - -• **hash**: `string` - -Hash of the current location. If present, starts with a `#`. - -#### Inherited from - -\_RouteLocationBase.hash - -___ - -### matched - -• **matched**: [`RouteRecordNormalized`](RouteRecordNormalized.md)[] - -Array of [RouteRecordNormalized](RouteRecordNormalized.md) - -___ - -### meta - -• **meta**: [`RouteMeta`](RouteMeta.md) - -Merged `meta` properties from all the matched route records. - -#### Inherited from - -\_RouteLocationBase.meta - -___ - -### name - -• **name**: `undefined` \| ``null`` \| [`RouteRecordName`](../index.md#RouteRecordName) - -Name of the matched record - -#### Inherited from - -\_RouteLocationBase.name - -___ - -### params - -• **params**: [`RouteParams`](../index.md#RouteParams) - -Object of decoded params extracted from the `path`. - -#### Inherited from - -\_RouteLocationBase.params - -___ - -### path - -• **path**: `string` - -Percentage encoded pathname section of the URL. - -#### Inherited from - -\_RouteLocationBase.path - -___ - -### query - -• **query**: [`LocationQuery`](../index.md#LocationQuery) - -Object representation of the `search` property of the current location. - -#### Inherited from - -\_RouteLocationBase.query - -___ - -### redirectedFrom - -• **redirectedFrom**: `undefined` \| [`RouteLocation`](RouteLocation.md) - -Contains the location we were initially trying to access before ending up -on the current location. - -#### Inherited from - -\_RouteLocationBase.redirectedFrom diff --git a/packages/docs/api/interfaces/RouteLocationNormalizedGeneric.md b/packages/docs/api/interfaces/RouteLocationNormalizedGeneric.md new file mode 100644 index 000000000..ac25d6dbc --- /dev/null +++ b/packages/docs/api/interfaces/RouteLocationNormalizedGeneric.md @@ -0,0 +1,125 @@ +--- +editLink: false +--- + +[API Documentation](../index.md) / RouteLocationNormalizedGeneric + +# Interface: RouteLocationNormalizedGeneric + +Generic version of [RouteLocationNormalized](../index.md#RouteLocationNormalized) that is used when no [RouteMap](../index.md#RouteMap) is provided. + +## Hierarchy + +- [`_RouteLocationBase`](RouteLocationBase.md) + + ↳ **`RouteLocationNormalizedGeneric`** + + ↳↳ [`RouteLocationNormalizedTyped`](RouteLocationNormalizedTyped.md) + + ↳↳ [`RouteLocationNormalizedLoadedGeneric`](RouteLocationNormalizedLoadedGeneric.md) + +## Properties + +### fullPath + +• **fullPath**: `string` + +The whole location including the `search` and `hash`. This string is +percentage encoded. + +#### Inherited from + +[_RouteLocationBase](RouteLocationBase.md).[fullPath](RouteLocationBase.md#fullPath) + +___ + +### hash + +• **hash**: `string` + +Hash of the current location. If present, starts with a `#`. + +#### Inherited from + +[_RouteLocationBase](RouteLocationBase.md).[hash](RouteLocationBase.md#hash) + +___ + +### matched + +• **matched**: [`RouteRecordNormalized`](RouteRecordNormalized.md)[] + +Array of [RouteRecordNormalized](RouteRecordNormalized.md) + +___ + +### meta + +• **meta**: [`RouteMeta`](RouteMeta.md) + +Merged `meta` properties from all the matched route records. + +#### Inherited from + +[_RouteLocationBase](RouteLocationBase.md).[meta](RouteLocationBase.md#meta) + +___ + +### name + +• **name**: [`RouteRecordNameGeneric`](../index.md#RouteRecordNameGeneric) + +Name of the matched record + +#### Overrides + +[_RouteLocationBase](RouteLocationBase.md).[name](RouteLocationBase.md#name) + +___ + +### params + +• **params**: [`RouteParamsGeneric`](../index.md#RouteParamsGeneric) + +Object of decoded params extracted from the `path`. + +#### Overrides + +[_RouteLocationBase](RouteLocationBase.md).[params](RouteLocationBase.md#params) + +___ + +### path + +• **path**: `string` + +Percentage encoded pathname section of the URL. + +#### Inherited from + +[_RouteLocationBase](RouteLocationBase.md).[path](RouteLocationBase.md#path) + +___ + +### query + +• **query**: [`LocationQuery`](../index.md#LocationQuery) + +Object representation of the `search` property of the current location. + +#### Inherited from + +[_RouteLocationBase](RouteLocationBase.md).[query](RouteLocationBase.md#query) + +___ + +### redirectedFrom + +• **redirectedFrom**: `undefined` \| [`RouteLocationGeneric`](RouteLocationGeneric.md) + +Contains the location we were initially trying to access before ending up +on the current location. + +#### Inherited from + +[_RouteLocationBase](RouteLocationBase.md).[redirectedFrom](RouteLocationBase.md#redirectedFrom) diff --git a/packages/docs/api/interfaces/RouteLocationNormalizedLoaded.md b/packages/docs/api/interfaces/RouteLocationNormalizedLoaded.md deleted file mode 100644 index 79b028385..000000000 --- a/packages/docs/api/interfaces/RouteLocationNormalizedLoaded.md +++ /dev/null @@ -1,124 +0,0 @@ ---- -editLink: false ---- - -[API Documentation](../index.md) / RouteLocationNormalizedLoaded - -# Interface: RouteLocationNormalizedLoaded - -[RouteLocationRaw](../index.md#RouteLocationRaw) with - -## Hierarchy - -- `_RouteLocationBase` - - ↳ **`RouteLocationNormalizedLoaded`** - -## Properties - -### fullPath - -• **fullPath**: `string` - -The whole location including the `search` and `hash`. This string is -percentage encoded. - -#### Inherited from - -\_RouteLocationBase.fullPath - -___ - -### hash - -• **hash**: `string` - -Hash of the current location. If present, starts with a `#`. - -#### Inherited from - -\_RouteLocationBase.hash - -___ - -### matched - -• **matched**: [`RouteLocationMatched`](RouteLocationMatched.md)[] - -Array of [RouteLocationMatched](RouteLocationMatched.md) containing only plain components (any -lazy-loaded components have been loaded and were replaced inside the -`components` object) so it can be directly used to display routes. It -cannot contain redirect records either - -___ - -### meta - -• **meta**: [`RouteMeta`](RouteMeta.md) - -Merged `meta` properties from all the matched route records. - -#### Inherited from - -\_RouteLocationBase.meta - -___ - -### name - -• **name**: `undefined` \| ``null`` \| [`RouteRecordName`](../index.md#RouteRecordName) - -Name of the matched record - -#### Inherited from - -\_RouteLocationBase.name - -___ - -### params - -• **params**: [`RouteParams`](../index.md#RouteParams) - -Object of decoded params extracted from the `path`. - -#### Inherited from - -\_RouteLocationBase.params - -___ - -### path - -• **path**: `string` - -Percentage encoded pathname section of the URL. - -#### Inherited from - -\_RouteLocationBase.path - -___ - -### query - -• **query**: [`LocationQuery`](../index.md#LocationQuery) - -Object representation of the `search` property of the current location. - -#### Inherited from - -\_RouteLocationBase.query - -___ - -### redirectedFrom - -• **redirectedFrom**: `undefined` \| [`RouteLocation`](RouteLocation.md) - -Contains the location we were initially trying to access before ending up -on the current location. - -#### Inherited from - -\_RouteLocationBase.redirectedFrom diff --git a/packages/docs/api/interfaces/RouteLocationNormalizedLoadedGeneric.md b/packages/docs/api/interfaces/RouteLocationNormalizedLoadedGeneric.md new file mode 100644 index 000000000..45c28e7cf --- /dev/null +++ b/packages/docs/api/interfaces/RouteLocationNormalizedLoadedGeneric.md @@ -0,0 +1,130 @@ +--- +editLink: false +--- + +[API Documentation](../index.md) / RouteLocationNormalizedLoadedGeneric + +# Interface: RouteLocationNormalizedLoadedGeneric + +Generic version of [RouteLocationNormalizedLoaded](../index.md#RouteLocationNormalizedLoaded) that is used when no [RouteMap](../index.md#RouteMap) is provided. + +## Hierarchy + +- [`RouteLocationNormalizedGeneric`](RouteLocationNormalizedGeneric.md) + + ↳ **`RouteLocationNormalizedLoadedGeneric`** + + ↳↳ [`RouteLocationNormalizedLoadedTyped`](RouteLocationNormalizedLoadedTyped.md) + +## Properties + +### fullPath + +• **fullPath**: `string` + +The whole location including the `search` and `hash`. This string is +percentage encoded. + +#### Inherited from + +[RouteLocationNormalizedGeneric](RouteLocationNormalizedGeneric.md).[fullPath](RouteLocationNormalizedGeneric.md#fullPath) + +___ + +### hash + +• **hash**: `string` + +Hash of the current location. If present, starts with a `#`. + +#### Inherited from + +[RouteLocationNormalizedGeneric](RouteLocationNormalizedGeneric.md).[hash](RouteLocationNormalizedGeneric.md#hash) + +___ + +### matched + +• **matched**: [`RouteLocationMatched`](RouteLocationMatched.md)[] + +Array of [RouteLocationMatched](RouteLocationMatched.md) containing only plain components (any +lazy-loaded components have been loaded and were replaced inside the +`components` object) so it can be directly used to display routes. It +cannot contain redirect records either. **This property is non-enumerable**. + +#### Overrides + +[RouteLocationNormalizedGeneric](RouteLocationNormalizedGeneric.md).[matched](RouteLocationNormalizedGeneric.md#matched) + +___ + +### meta + +• **meta**: [`RouteMeta`](RouteMeta.md) + +Merged `meta` properties from all the matched route records. + +#### Inherited from + +[RouteLocationNormalizedGeneric](RouteLocationNormalizedGeneric.md).[meta](RouteLocationNormalizedGeneric.md#meta) + +___ + +### name + +• **name**: [`RouteRecordNameGeneric`](../index.md#RouteRecordNameGeneric) + +Name of the matched record + +#### Inherited from + +[RouteLocationNormalizedGeneric](RouteLocationNormalizedGeneric.md).[name](RouteLocationNormalizedGeneric.md#name) + +___ + +### params + +• **params**: [`RouteParamsGeneric`](../index.md#RouteParamsGeneric) + +Object of decoded params extracted from the `path`. + +#### Inherited from + +[RouteLocationNormalizedGeneric](RouteLocationNormalizedGeneric.md).[params](RouteLocationNormalizedGeneric.md#params) + +___ + +### path + +• **path**: `string` + +Percentage encoded pathname section of the URL. + +#### Inherited from + +[RouteLocationNormalizedGeneric](RouteLocationNormalizedGeneric.md).[path](RouteLocationNormalizedGeneric.md#path) + +___ + +### query + +• **query**: [`LocationQuery`](../index.md#LocationQuery) + +Object representation of the `search` property of the current location. + +#### Inherited from + +[RouteLocationNormalizedGeneric](RouteLocationNormalizedGeneric.md).[query](RouteLocationNormalizedGeneric.md#query) + +___ + +### redirectedFrom + +• **redirectedFrom**: `undefined` \| [`RouteLocationGeneric`](RouteLocationGeneric.md) + +Contains the location we were initially trying to access before ending up +on the current location. + +#### Inherited from + +[RouteLocationNormalizedGeneric](RouteLocationNormalizedGeneric.md).[redirectedFrom](RouteLocationNormalizedGeneric.md#redirectedFrom) diff --git a/packages/docs/api/interfaces/RouteLocationNormalizedLoadedTyped.md b/packages/docs/api/interfaces/RouteLocationNormalizedLoadedTyped.md new file mode 100644 index 000000000..e09690e08 --- /dev/null +++ b/packages/docs/api/interfaces/RouteLocationNormalizedLoadedTyped.md @@ -0,0 +1,135 @@ +--- +editLink: false +--- + +[API Documentation](../index.md) / RouteLocationNormalizedLoadedTyped + +# Interface: RouteLocationNormalizedLoadedTyped\ + +Helper to generate a type safe version of the [RouteLocationNormalizedLoaded](../index.md#RouteLocationNormalizedLoaded) type. + +## Type parameters + +| Name | Type | +| :------ | :------ | +| `RouteMap` | extends [`RouteMapGeneric`](../index.md#RouteMapGeneric) = [`RouteMapGeneric`](../index.md#RouteMapGeneric) | +| `Name` | extends keyof `RouteMap` = keyof `RouteMap` | + +## Hierarchy + +- [`RouteLocationNormalizedLoadedGeneric`](RouteLocationNormalizedLoadedGeneric.md) + + ↳ **`RouteLocationNormalizedLoadedTyped`** + +## Properties + +### fullPath + +• **fullPath**: `string` + +The whole location including the `search` and `hash`. This string is +percentage encoded. + +#### Inherited from + +[RouteLocationNormalizedLoadedGeneric](RouteLocationNormalizedLoadedGeneric.md).[fullPath](RouteLocationNormalizedLoadedGeneric.md#fullPath) + +___ + +### hash + +• **hash**: `string` + +Hash of the current location. If present, starts with a `#`. + +#### Inherited from + +[RouteLocationNormalizedLoadedGeneric](RouteLocationNormalizedLoadedGeneric.md).[hash](RouteLocationNormalizedLoadedGeneric.md#hash) + +___ + +### matched + +• **matched**: [`RouteLocationMatched`](RouteLocationMatched.md)[] + +Array of [RouteLocationMatched](RouteLocationMatched.md) containing only plain components (any +lazy-loaded components have been loaded and were replaced inside the +`components` object) so it can be directly used to display routes. It +cannot contain redirect records either. **This property is non-enumerable**. + +#### Inherited from + +[RouteLocationNormalizedLoadedGeneric](RouteLocationNormalizedLoadedGeneric.md).[matched](RouteLocationNormalizedLoadedGeneric.md#matched) + +___ + +### meta + +• **meta**: [`RouteMeta`](RouteMeta.md) + +Merged `meta` properties from all the matched route records. + +#### Inherited from + +[RouteLocationNormalizedLoadedGeneric](RouteLocationNormalizedLoadedGeneric.md).[meta](RouteLocationNormalizedLoadedGeneric.md#meta) + +___ + +### name + +• **name**: `Extract`\<`Name`, `string` \| `symbol`\> + +Name of the matched record + +#### Overrides + +[RouteLocationNormalizedLoadedGeneric](RouteLocationNormalizedLoadedGeneric.md).[name](RouteLocationNormalizedLoadedGeneric.md#name) + +___ + +### params + +• **params**: `RouteMap`[`Name`][``"params"``] + +Object of decoded params extracted from the `path`. + +#### Overrides + +[RouteLocationNormalizedLoadedGeneric](RouteLocationNormalizedLoadedGeneric.md).[params](RouteLocationNormalizedLoadedGeneric.md#params) + +___ + +### path + +• **path**: `string` + +Percentage encoded pathname section of the URL. + +#### Inherited from + +[RouteLocationNormalizedLoadedGeneric](RouteLocationNormalizedLoadedGeneric.md).[path](RouteLocationNormalizedLoadedGeneric.md#path) + +___ + +### query + +• **query**: [`LocationQuery`](../index.md#LocationQuery) + +Object representation of the `search` property of the current location. + +#### Inherited from + +[RouteLocationNormalizedLoadedGeneric](RouteLocationNormalizedLoadedGeneric.md).[query](RouteLocationNormalizedLoadedGeneric.md#query) + +___ + +### redirectedFrom + +• **redirectedFrom**: `undefined` \| [`RouteLocationGeneric`](RouteLocationGeneric.md) + +Contains the location we were initially trying to access before ending up +on the current location. + +#### Inherited from + +[RouteLocationNormalizedLoadedGeneric](RouteLocationNormalizedLoadedGeneric.md).[redirectedFrom](RouteLocationNormalizedLoadedGeneric.md#redirectedFrom) diff --git a/packages/docs/api/interfaces/RouteLocationNormalizedTyped.md b/packages/docs/api/interfaces/RouteLocationNormalizedTyped.md new file mode 100644 index 000000000..58ff01b6c --- /dev/null +++ b/packages/docs/api/interfaces/RouteLocationNormalizedTyped.md @@ -0,0 +1,132 @@ +--- +editLink: false +--- + +[API Documentation](../index.md) / RouteLocationNormalizedTyped + +# Interface: RouteLocationNormalizedTyped\ + +Helper to generate a type safe version of the [RouteLocationNormalized](../index.md#RouteLocationNormalized) type. + +## Type parameters + +| Name | Type | +| :------ | :------ | +| `RouteMap` | extends [`RouteMapGeneric`](../index.md#RouteMapGeneric) = [`RouteMapGeneric`](../index.md#RouteMapGeneric) | +| `Name` | extends keyof `RouteMap` = keyof `RouteMap` | + +## Hierarchy + +- [`RouteLocationNormalizedGeneric`](RouteLocationNormalizedGeneric.md) + + ↳ **`RouteLocationNormalizedTyped`** + +## Properties + +### fullPath + +• **fullPath**: `string` + +The whole location including the `search` and `hash`. This string is +percentage encoded. + +#### Inherited from + +[RouteLocationNormalizedGeneric](RouteLocationNormalizedGeneric.md).[fullPath](RouteLocationNormalizedGeneric.md#fullPath) + +___ + +### hash + +• **hash**: `string` + +Hash of the current location. If present, starts with a `#`. + +#### Inherited from + +[RouteLocationNormalizedGeneric](RouteLocationNormalizedGeneric.md).[hash](RouteLocationNormalizedGeneric.md#hash) + +___ + +### matched + +• **matched**: [`RouteRecordNormalized`](RouteRecordNormalized.md)[] + +Array of [RouteRecordNormalized](RouteRecordNormalized.md) + +#### Overrides + +[RouteLocationNormalizedGeneric](RouteLocationNormalizedGeneric.md).[matched](RouteLocationNormalizedGeneric.md#matched) + +___ + +### meta + +• **meta**: [`RouteMeta`](RouteMeta.md) + +Merged `meta` properties from all the matched route records. + +#### Inherited from + +[RouteLocationNormalizedGeneric](RouteLocationNormalizedGeneric.md).[meta](RouteLocationNormalizedGeneric.md#meta) + +___ + +### name + +• **name**: `Extract`\<`Name`, `string` \| `symbol`\> + +Name of the matched record + +#### Overrides + +[RouteLocationNormalizedGeneric](RouteLocationNormalizedGeneric.md).[name](RouteLocationNormalizedGeneric.md#name) + +___ + +### params + +• **params**: `RouteMap`[`Name`][``"params"``] + +Object of decoded params extracted from the `path`. + +#### Overrides + +[RouteLocationNormalizedGeneric](RouteLocationNormalizedGeneric.md).[params](RouteLocationNormalizedGeneric.md#params) + +___ + +### path + +• **path**: `string` + +Percentage encoded pathname section of the URL. + +#### Inherited from + +[RouteLocationNormalizedGeneric](RouteLocationNormalizedGeneric.md).[path](RouteLocationNormalizedGeneric.md#path) + +___ + +### query + +• **query**: [`LocationQuery`](../index.md#LocationQuery) + +Object representation of the `search` property of the current location. + +#### Inherited from + +[RouteLocationNormalizedGeneric](RouteLocationNormalizedGeneric.md).[query](RouteLocationNormalizedGeneric.md#query) + +___ + +### redirectedFrom + +• **redirectedFrom**: `undefined` \| [`RouteLocationGeneric`](RouteLocationGeneric.md) + +Contains the location we were initially trying to access before ending up +on the current location. + +#### Inherited from + +[RouteLocationNormalizedGeneric](RouteLocationNormalizedGeneric.md).[redirectedFrom](RouteLocationNormalizedGeneric.md#redirectedFrom) diff --git a/packages/docs/api/interfaces/RouteLocationOptions.md b/packages/docs/api/interfaces/RouteLocationOptions.md index 59ece3525..d64f6c606 100644 --- a/packages/docs/api/interfaces/RouteLocationOptions.md +++ b/packages/docs/api/interfaces/RouteLocationOptions.md @@ -8,6 +8,18 @@ editLink: false Common options for all navigation methods. +## Hierarchy + +- **`RouteLocationOptions`** + + ↳ [`RouteLocationNamedRaw`](RouteLocationNamedRaw.md) + + ↳ [`RouteLocationPathRaw`](RouteLocationPathRaw.md) + + ↳ [`RouteLocationAsRelativeGeneric`](RouteLocationAsRelativeGeneric.md) + + ↳ [`RouteLocationAsPathGeneric`](RouteLocationAsPathGeneric.md) + ## Properties ### force diff --git a/packages/docs/api/interfaces/RouteLocationPathRaw.md b/packages/docs/api/interfaces/RouteLocationPathRaw.md new file mode 100644 index 000000000..631aa06b8 --- /dev/null +++ b/packages/docs/api/interfaces/RouteLocationPathRaw.md @@ -0,0 +1,89 @@ +--- +editLink: false +--- + +[API Documentation](../index.md) / RouteLocationPathRaw + +# Interface: RouteLocationPathRaw + +Route Location that can infer the possible paths. + +## Hierarchy + +- [`RouteQueryAndHash`](RouteQueryAndHash.md) + +- [`MatcherLocationAsPath`](MatcherLocationAsPath.md) + +- [`RouteLocationOptions`](RouteLocationOptions.md) + + ↳ **`RouteLocationPathRaw`** + +## Properties + +### force + +• `Optional` **force**: `boolean` + +Triggers the navigation even if the location is the same as the current one. +Note this will also add a new entry to the history unless `replace: true` +is passed. + +#### Inherited from + +[RouteLocationOptions](RouteLocationOptions.md).[force](RouteLocationOptions.md#force) + +___ + +### hash + +• `Optional` **hash**: `string` + +#### Inherited from + +[RouteQueryAndHash](RouteQueryAndHash.md).[hash](RouteQueryAndHash.md#hash) + +___ + +### path + +• **path**: `string` + +#### Inherited from + +[MatcherLocationAsPath](MatcherLocationAsPath.md).[path](MatcherLocationAsPath.md#path) + +___ + +### query + +• `Optional` **query**: [`LocationQueryRaw`](../index.md#LocationQueryRaw) + +#### Inherited from + +[RouteQueryAndHash](RouteQueryAndHash.md).[query](RouteQueryAndHash.md#query) + +___ + +### replace + +• `Optional` **replace**: `boolean` + +Replace the entry in the history instead of pushing a new entry + +#### Inherited from + +[RouteLocationOptions](RouteLocationOptions.md).[replace](RouteLocationOptions.md#replace) + +___ + +### state + +• `Optional` **state**: [`HistoryState`](HistoryState.md) + +State to save using the History API. This cannot contain any reactive +values and some primitives like Symbols are forbidden. More info at +https://developer.mozilla.org/en-US/docs/Web/API/History/state + +#### Inherited from + +[RouteLocationOptions](RouteLocationOptions.md).[state](RouteLocationOptions.md#state) diff --git a/packages/docs/api/interfaces/RouteLocationResolvedGeneric.md b/packages/docs/api/interfaces/RouteLocationResolvedGeneric.md new file mode 100644 index 000000000..842c9a04f --- /dev/null +++ b/packages/docs/api/interfaces/RouteLocationResolvedGeneric.md @@ -0,0 +1,135 @@ +--- +editLink: false +--- + +[API Documentation](../index.md) / RouteLocationResolvedGeneric + +# Interface: RouteLocationResolvedGeneric + +Generic version of [RouteLocationResolved](../index.md#RouteLocationResolved). It is used when no [RouteMap](../index.md#RouteMap) is provided. + +## Hierarchy + +- [`RouteLocationGeneric`](RouteLocationGeneric.md) + + ↳ **`RouteLocationResolvedGeneric`** + +## Properties + +### fullPath + +• **fullPath**: `string` + +The whole location including the `search` and `hash`. This string is +percentage encoded. + +#### Inherited from + +[RouteLocationGeneric](RouteLocationGeneric.md).[fullPath](RouteLocationGeneric.md#fullPath) + +___ + +### hash + +• **hash**: `string` + +Hash of the current location. If present, starts with a `#`. + +#### Inherited from + +[RouteLocationGeneric](RouteLocationGeneric.md).[hash](RouteLocationGeneric.md#hash) + +___ + +### href + +• **href**: `string` + +Resolved `href` for the route location that will be set on the ``. + +___ + +### matched + +• **matched**: [`RouteRecordNormalized`](RouteRecordNormalized.md)[] + +Array of [RouteRecord](../index.md#RouteRecord) containing components as they were +passed when adding records. It can also contain redirect records. This +can't be used directly. **This property is non-enumerable**. + +#### Inherited from + +[RouteLocationGeneric](RouteLocationGeneric.md).[matched](RouteLocationGeneric.md#matched) + +___ + +### meta + +• **meta**: [`RouteMeta`](RouteMeta.md) + +Merged `meta` properties from all the matched route records. + +#### Inherited from + +[RouteLocationGeneric](RouteLocationGeneric.md).[meta](RouteLocationGeneric.md#meta) + +___ + +### name + +• **name**: ``null`` \| [`RouteRecordNameGeneric`](../index.md#RouteRecordNameGeneric) + +Name of the matched record + +#### Inherited from + +[RouteLocationGeneric](RouteLocationGeneric.md).[name](RouteLocationGeneric.md#name) + +___ + +### params + +• **params**: [`RouteParamsGeneric`](../index.md#RouteParamsGeneric) + +Object of decoded params extracted from the `path`. + +#### Inherited from + +[RouteLocationGeneric](RouteLocationGeneric.md).[params](RouteLocationGeneric.md#params) + +___ + +### path + +• **path**: `string` + +Percentage encoded pathname section of the URL. + +#### Inherited from + +[RouteLocationGeneric](RouteLocationGeneric.md).[path](RouteLocationGeneric.md#path) + +___ + +### query + +• **query**: [`LocationQuery`](../index.md#LocationQuery) + +Object representation of the `search` property of the current location. + +#### Inherited from + +[RouteLocationGeneric](RouteLocationGeneric.md).[query](RouteLocationGeneric.md#query) + +___ + +### redirectedFrom + +• **redirectedFrom**: `undefined` \| [`RouteLocationGeneric`](RouteLocationGeneric.md) + +Contains the location we were initially trying to access before ending up +on the current location. + +#### Inherited from + +[RouteLocationGeneric](RouteLocationGeneric.md).[redirectedFrom](RouteLocationGeneric.md#redirectedFrom) diff --git a/packages/docs/api/interfaces/RouteLocationResolvedTyped.md b/packages/docs/api/interfaces/RouteLocationResolvedTyped.md new file mode 100644 index 000000000..8089756c3 --- /dev/null +++ b/packages/docs/api/interfaces/RouteLocationResolvedTyped.md @@ -0,0 +1,142 @@ +--- +editLink: false +--- + +[API Documentation](../index.md) / RouteLocationResolvedTyped + +# Interface: RouteLocationResolvedTyped\ + +Helper to generate a type safe version of the [RouteLocationResolved](../index.md#RouteLocationResolved) type. + +## Type parameters + +| Name | Type | +| :------ | :------ | +| `RouteMap` | extends [`RouteMapGeneric`](../index.md#RouteMapGeneric) | +| `Name` | extends keyof `RouteMap` | + +## Hierarchy + +- [`RouteLocationTyped`](RouteLocationTyped.md)\<`RouteMap`, `Name`\> + + ↳ **`RouteLocationResolvedTyped`** + +## Properties + +### fullPath + +• **fullPath**: `string` + +The whole location including the `search` and `hash`. This string is +percentage encoded. + +#### Inherited from + +[RouteLocationTyped](RouteLocationTyped.md).[fullPath](RouteLocationTyped.md#fullPath) + +___ + +### hash + +• **hash**: `string` + +Hash of the current location. If present, starts with a `#`. + +#### Inherited from + +[RouteLocationTyped](RouteLocationTyped.md).[hash](RouteLocationTyped.md#hash) + +___ + +### href + +• **href**: `string` + +Resolved `href` for the route location that will be set on the ``. + +___ + +### matched + +• **matched**: [`RouteRecordNormalized`](RouteRecordNormalized.md)[] + +Array of [RouteRecord](../index.md#RouteRecord) containing components as they were +passed when adding records. It can also contain redirect records. This +can't be used directly. **This property is non-enumerable**. + +#### Inherited from + +[RouteLocationTyped](RouteLocationTyped.md).[matched](RouteLocationTyped.md#matched) + +___ + +### meta + +• **meta**: [`RouteMeta`](RouteMeta.md) + +Merged `meta` properties from all the matched route records. + +#### Inherited from + +[RouteLocationTyped](RouteLocationTyped.md).[meta](RouteLocationTyped.md#meta) + +___ + +### name + +• **name**: `Extract`\<`Name`, `string` \| `symbol`\> + +Name of the matched record + +#### Inherited from + +[RouteLocationTyped](RouteLocationTyped.md).[name](RouteLocationTyped.md#name) + +___ + +### params + +• **params**: `RouteMap`[`Name`][``"params"``] + +Object of decoded params extracted from the `path`. + +#### Inherited from + +[RouteLocationTyped](RouteLocationTyped.md).[params](RouteLocationTyped.md#params) + +___ + +### path + +• **path**: `string` + +Percentage encoded pathname section of the URL. + +#### Inherited from + +[RouteLocationTyped](RouteLocationTyped.md).[path](RouteLocationTyped.md#path) + +___ + +### query + +• **query**: [`LocationQuery`](../index.md#LocationQuery) + +Object representation of the `search` property of the current location. + +#### Inherited from + +[RouteLocationTyped](RouteLocationTyped.md).[query](RouteLocationTyped.md#query) + +___ + +### redirectedFrom + +• **redirectedFrom**: `undefined` \| [`RouteLocationGeneric`](RouteLocationGeneric.md) + +Contains the location we were initially trying to access before ending up +on the current location. + +#### Inherited from + +[RouteLocationTyped](RouteLocationTyped.md).[redirectedFrom](RouteLocationTyped.md#redirectedFrom) diff --git a/packages/docs/api/interfaces/RouteLocationTyped.md b/packages/docs/api/interfaces/RouteLocationTyped.md new file mode 100644 index 000000000..9d0debb4a --- /dev/null +++ b/packages/docs/api/interfaces/RouteLocationTyped.md @@ -0,0 +1,136 @@ +--- +editLink: false +--- + +[API Documentation](../index.md) / RouteLocationTyped + +# Interface: RouteLocationTyped\ + +Helper to generate a type safe version of the [RouteLocation](../index.md#RouteLocation) type. + +## Type parameters + +| Name | Type | +| :------ | :------ | +| `RouteMap` | extends [`RouteMapGeneric`](../index.md#RouteMapGeneric) | +| `Name` | extends keyof `RouteMap` | + +## Hierarchy + +- [`RouteLocationGeneric`](RouteLocationGeneric.md) + + ↳ **`RouteLocationTyped`** + + ↳↳ [`RouteLocationResolvedTyped`](RouteLocationResolvedTyped.md) + +## Properties + +### fullPath + +• **fullPath**: `string` + +The whole location including the `search` and `hash`. This string is +percentage encoded. + +#### Inherited from + +[RouteLocationGeneric](RouteLocationGeneric.md).[fullPath](RouteLocationGeneric.md#fullPath) + +___ + +### hash + +• **hash**: `string` + +Hash of the current location. If present, starts with a `#`. + +#### Inherited from + +[RouteLocationGeneric](RouteLocationGeneric.md).[hash](RouteLocationGeneric.md#hash) + +___ + +### matched + +• **matched**: [`RouteRecordNormalized`](RouteRecordNormalized.md)[] + +Array of [RouteRecord](../index.md#RouteRecord) containing components as they were +passed when adding records. It can also contain redirect records. This +can't be used directly. **This property is non-enumerable**. + +#### Inherited from + +[RouteLocationGeneric](RouteLocationGeneric.md).[matched](RouteLocationGeneric.md#matched) + +___ + +### meta + +• **meta**: [`RouteMeta`](RouteMeta.md) + +Merged `meta` properties from all the matched route records. + +#### Inherited from + +[RouteLocationGeneric](RouteLocationGeneric.md).[meta](RouteLocationGeneric.md#meta) + +___ + +### name + +• **name**: `Extract`\<`Name`, `string` \| `symbol`\> + +Name of the matched record + +#### Overrides + +[RouteLocationGeneric](RouteLocationGeneric.md).[name](RouteLocationGeneric.md#name) + +___ + +### params + +• **params**: `RouteMap`[`Name`][``"params"``] + +Object of decoded params extracted from the `path`. + +#### Overrides + +[RouteLocationGeneric](RouteLocationGeneric.md).[params](RouteLocationGeneric.md#params) + +___ + +### path + +• **path**: `string` + +Percentage encoded pathname section of the URL. + +#### Inherited from + +[RouteLocationGeneric](RouteLocationGeneric.md).[path](RouteLocationGeneric.md#path) + +___ + +### query + +• **query**: [`LocationQuery`](../index.md#LocationQuery) + +Object representation of the `search` property of the current location. + +#### Inherited from + +[RouteLocationGeneric](RouteLocationGeneric.md).[query](RouteLocationGeneric.md#query) + +___ + +### redirectedFrom + +• **redirectedFrom**: `undefined` \| [`RouteLocationGeneric`](RouteLocationGeneric.md) + +Contains the location we were initially trying to access before ending up +on the current location. + +#### Inherited from + +[RouteLocationGeneric](RouteLocationGeneric.md).[redirectedFrom](RouteLocationGeneric.md#redirectedFrom) diff --git a/packages/docs/api/interfaces/RouteMeta.md b/packages/docs/api/interfaces/RouteMeta.md index 5e6007b10..0c2a36e4f 100644 --- a/packages/docs/api/interfaces/RouteMeta.md +++ b/packages/docs/api/interfaces/RouteMeta.md @@ -18,7 +18,7 @@ declare module 'vue-router' { interface RouteMeta { requiresAuth?: boolean } - } +} ``` ## Hierarchy diff --git a/packages/docs/api/interfaces/RouteQueryAndHash.md b/packages/docs/api/interfaces/RouteQueryAndHash.md new file mode 100644 index 000000000..b501ff5ab --- /dev/null +++ b/packages/docs/api/interfaces/RouteQueryAndHash.md @@ -0,0 +1,31 @@ +--- +editLink: false +--- + +[API Documentation](../index.md) / RouteQueryAndHash + +# Interface: RouteQueryAndHash + +## Hierarchy + +- **`RouteQueryAndHash`** + + ↳ [`RouteLocationNamedRaw`](RouteLocationNamedRaw.md) + + ↳ [`RouteLocationPathRaw`](RouteLocationPathRaw.md) + + ↳ [`RouteLocationAsRelativeGeneric`](RouteLocationAsRelativeGeneric.md) + + ↳ [`RouteLocationAsPathGeneric`](RouteLocationAsPathGeneric.md) + +## Properties + +### hash + +• `Optional` **hash**: `string` + +___ + +### query + +• `Optional` **query**: [`LocationQueryRaw`](../index.md#LocationQueryRaw) diff --git a/packages/docs/api/interfaces/RouteRecordBase.md b/packages/docs/api/interfaces/RouteRecordBase.md index f64004047..7fb4d708a 100644 --- a/packages/docs/api/interfaces/RouteRecordBase.md +++ b/packages/docs/api/interfaces/RouteRecordBase.md @@ -79,7 +79,7 @@ ___ ### name -• `Optional` **name**: [`RouteRecordName`](../index.md#RouteRecordName) +• `Optional` **name**: [`RouteRecordNameGeneric`](../index.md#RouteRecordNameGeneric) Name for the route record. Must be unique. @@ -102,7 +102,7 @@ ___ ### props -• `Optional` **props**: `_RouteRecordProps` \| `Record`\<`string`, `_RouteRecordProps`\> +• `Optional` **props**: [`_RouteRecordProps`](../index.md#_RouteRecordProps) \| `Record`\<`string`, [`_RouteRecordProps`](../index.md#_RouteRecordProps)\> Allow passing down params as props to the component rendered by `router-view`. @@ -110,7 +110,7 @@ ___ ### redirect -• `Optional` **redirect**: `RouteRecordRedirectOption` +• `Optional` **redirect**: [`RouteRecordRedirectOption`](../index.md#RouteRecordRedirectOption) Where to redirect if the route is directly matched. The redirection happens before any navigation guard and triggers a new navigation with the new diff --git a/packages/docs/api/interfaces/RouteRecordInfo.md b/packages/docs/api/interfaces/RouteRecordInfo.md new file mode 100644 index 000000000..fa078d760 --- /dev/null +++ b/packages/docs/api/interfaces/RouteRecordInfo.md @@ -0,0 +1,53 @@ +--- +editLink: false +--- + +[API Documentation](../index.md) / RouteRecordInfo + +# Interface: RouteRecordInfo\ + +Helper type to define a Typed `RouteRecord` + +**`See`** + +[RouteRecord](../index.md#RouteRecord) + +## Type parameters + +| Name | Type | +| :------ | :------ | +| `Name` | extends `string` \| `symbol` = `string` | +| `Path` | extends `string` = `string` | +| `ParamsRaw` | extends [`RouteParamsRawGeneric`](../index.md#RouteParamsRawGeneric) = [`RouteParamsRawGeneric`](../index.md#RouteParamsRawGeneric) | +| `Params` | extends [`RouteParamsGeneric`](../index.md#RouteParamsGeneric) = [`RouteParamsGeneric`](../index.md#RouteParamsGeneric) | +| `Meta` | extends [`RouteMeta`](RouteMeta.md) = [`RouteMeta`](RouteMeta.md) | + +## Properties + +### meta + +• **meta**: `Meta` + +___ + +### name + +• **name**: `Name` + +___ + +### params + +• **params**: `Params` + +___ + +### paramsRaw + +• **paramsRaw**: `ParamsRaw` + +___ + +### path + +• **path**: `Path` diff --git a/packages/docs/api/interfaces/RouteRecordMultipleViews.md b/packages/docs/api/interfaces/RouteRecordMultipleViews.md index 2f5007aa5..9d8d475be 100644 --- a/packages/docs/api/interfaces/RouteRecordMultipleViews.md +++ b/packages/docs/api/interfaces/RouteRecordMultipleViews.md @@ -99,7 +99,7 @@ ___ ### name -• `Optional` **name**: [`RouteRecordName`](../index.md#RouteRecordName) +• `Optional` **name**: [`RouteRecordNameGeneric`](../index.md#RouteRecordNameGeneric) Name for the route record. Must be unique. @@ -130,7 +130,7 @@ ___ ### props -• `Optional` **props**: `boolean` \| `Record`\<`string`, `_RouteRecordProps`\> +• `Optional` **props**: `boolean` \| `Record`\<`string`, [`_RouteRecordProps`](../index.md#_RouteRecordProps)\> Allow passing down params as props to the component rendered by `router-view`. Should be an object with the same keys as `components` or a diff --git a/packages/docs/api/interfaces/RouteRecordMultipleViewsWithChildren.md b/packages/docs/api/interfaces/RouteRecordMultipleViewsWithChildren.md index ddec0ecaf..1c8f55b7a 100644 --- a/packages/docs/api/interfaces/RouteRecordMultipleViewsWithChildren.md +++ b/packages/docs/api/interfaces/RouteRecordMultipleViewsWithChildren.md @@ -99,7 +99,7 @@ ___ ### name -• `Optional` **name**: [`RouteRecordName`](../index.md#RouteRecordName) +• `Optional` **name**: [`RouteRecordNameGeneric`](../index.md#RouteRecordNameGeneric) Name for the route record. Must be unique. @@ -130,7 +130,7 @@ ___ ### props -• `Optional` **props**: `boolean` \| `Record`\<`string`, `_RouteRecordProps`\> +• `Optional` **props**: `boolean` \| `Record`\<`string`, [`_RouteRecordProps`](../index.md#_RouteRecordProps)\> Allow passing down params as props to the component rendered by `router-view`. Should be an object with the same keys as `components` or a @@ -144,7 +144,7 @@ ___ ### redirect -• `Optional` **redirect**: `RouteRecordRedirectOption` +• `Optional` **redirect**: [`RouteRecordRedirectOption`](../index.md#RouteRecordRedirectOption) Where to redirect if the route is directly matched. The redirection happens before any navigation guard and triggers a new navigation with the new diff --git a/packages/docs/api/interfaces/RouteRecordNormalized.md b/packages/docs/api/interfaces/RouteRecordNormalized.md index 0107112b6..6e08887e6 100644 --- a/packages/docs/api/interfaces/RouteRecordNormalized.md +++ b/packages/docs/api/interfaces/RouteRecordNormalized.md @@ -49,6 +49,14 @@ Components to display when the URL matches this route. Allow using named views. ___ +### enterCallbacks + +• **enterCallbacks**: `Record`\<`string`, [`NavigationGuardNextCallback`](../index.md#NavigationGuardNextCallback)[]\> + +Registered beforeRouteEnter callbacks passed to `next` or returned in guards + +___ + ### instances • **instances**: `Record`\<`string`, `undefined` \| ``null`` \| `ComponentPublicInstance`\> @@ -63,6 +71,14 @@ views. ___ +### leaveGuards + +• **leaveGuards**: `Set`\<[`NavigationGuard`](NavigationGuard.md)\> + +Registered leave guards + +___ + ### meta • **meta**: [`RouteMeta`](RouteMeta.md) @@ -73,7 +89,7 @@ ___ ### name -• **name**: `undefined` \| [`RouteRecordName`](../index.md#RouteRecordName) +• **name**: [`RouteRecordNameGeneric`](../index.md#RouteRecordNameGeneric) Name for the route record. Must be unique. @@ -90,7 +106,7 @@ ___ ### props -• **props**: `Record`\<`string`, `_RouteRecordProps`\> +• **props**: `Record`\<`string`, [`_RouteRecordProps`](../index.md#_RouteRecordProps)\> Allow passing down params as props to the component rendered by `router-view`. Should be an object with the same keys as `components` or a @@ -100,8 +116,16 @@ ___ ### redirect -• **redirect**: `undefined` \| `RouteRecordRedirectOption` +• **redirect**: `undefined` \| [`RouteRecordRedirectOption`](../index.md#RouteRecordRedirectOption) Where to redirect if the route is directly matched. The redirection happens before any navigation guard and triggers a new navigation with the new target location. + +___ + +### updateGuards + +• **updateGuards**: `Set`\<[`NavigationGuard`](NavigationGuard.md)\> + +Registered update guards diff --git a/packages/docs/api/interfaces/RouteRecordRedirect.md b/packages/docs/api/interfaces/RouteRecordRedirect.md index 2f471ddd3..4129a36ab 100644 --- a/packages/docs/api/interfaces/RouteRecordRedirect.md +++ b/packages/docs/api/interfaces/RouteRecordRedirect.md @@ -98,7 +98,7 @@ ___ ### name -• `Optional` **name**: [`RouteRecordName`](../index.md#RouteRecordName) +• `Optional` **name**: [`RouteRecordNameGeneric`](../index.md#RouteRecordNameGeneric) Name for the route record. Must be unique. @@ -141,7 +141,7 @@ ___ ### redirect -• **redirect**: `RouteRecordRedirectOption` +• **redirect**: [`RouteRecordRedirectOption`](../index.md#RouteRecordRedirectOption) Where to redirect if the route is directly matched. The redirection happens before any navigation guard and triggers a new navigation with the new diff --git a/packages/docs/api/interfaces/RouteRecordSingleView.md b/packages/docs/api/interfaces/RouteRecordSingleView.md index 9a64196dc..7d6691808 100644 --- a/packages/docs/api/interfaces/RouteRecordSingleView.md +++ b/packages/docs/api/interfaces/RouteRecordSingleView.md @@ -99,7 +99,7 @@ ___ ### name -• `Optional` **name**: [`RouteRecordName`](../index.md#RouteRecordName) +• `Optional` **name**: [`RouteRecordNameGeneric`](../index.md#RouteRecordNameGeneric) Name for the route record. Must be unique. @@ -130,7 +130,7 @@ ___ ### props -• `Optional` **props**: `_RouteRecordProps` +• `Optional` **props**: [`_RouteRecordProps`](../index.md#_RouteRecordProps) Allow passing down params as props to the component rendered by `router-view`. diff --git a/packages/docs/api/interfaces/RouteRecordSingleViewWithChildren.md b/packages/docs/api/interfaces/RouteRecordSingleViewWithChildren.md index 2216c0d92..cc71c714f 100644 --- a/packages/docs/api/interfaces/RouteRecordSingleViewWithChildren.md +++ b/packages/docs/api/interfaces/RouteRecordSingleViewWithChildren.md @@ -99,7 +99,7 @@ ___ ### name -• `Optional` **name**: [`RouteRecordName`](../index.md#RouteRecordName) +• `Optional` **name**: [`RouteRecordNameGeneric`](../index.md#RouteRecordNameGeneric) Name for the route record. Must be unique. @@ -130,7 +130,7 @@ ___ ### props -• `Optional` **props**: `_RouteRecordProps` +• `Optional` **props**: [`_RouteRecordProps`](../index.md#_RouteRecordProps) Allow passing down params as props to the component rendered by `router-view`. @@ -142,7 +142,7 @@ ___ ### redirect -• `Optional` **redirect**: `RouteRecordRedirectOption` +• `Optional` **redirect**: [`RouteRecordRedirectOption`](../index.md#RouteRecordRedirectOption) Where to redirect if the route is directly matched. The redirection happens before any navigation guard and triggers a new navigation with the new diff --git a/packages/docs/api/interfaces/Router.md b/packages/docs/api/interfaces/Router.md index 9d7d79933..0e33a2d04 100644 --- a/packages/docs/api/interfaces/Router.md +++ b/packages/docs/api/interfaces/Router.md @@ -12,9 +12,9 @@ Router instance. ### currentRoute -• `Readonly` **currentRoute**: `Ref`\<[`RouteLocationNormalizedLoaded`](RouteLocationNormalizedLoaded.md)\> +• `Readonly` **currentRoute**: `Ref`\<[`RouteLocationNormalizedLoadedGeneric`](RouteLocationNormalizedLoadedGeneric.md)\> -Current [RouteLocationNormalized](RouteLocationNormalized.md) +Current [RouteLocationNormalized](../index.md#RouteLocationNormalized) ___ @@ -22,7 +22,7 @@ ___ • **listening**: `boolean` -Allows turning off the listening of history events. This is a low level api for micro-frontends. +Allows turning off the listening of history events. This is a low level api for micro-frontend. ___ @@ -44,7 +44,7 @@ Add a new [route record](../index.md#RouteRecordRaw) as the child of an existing | Name | Type | Description | | :------ | :------ | :------ | -| `parentName` | [`RouteRecordName`](../index.md#RouteRecordName) | Parent Route Record where `route` should be appended at | +| `parentName` | `NonNullable`\<[`RouteRecordNameGeneric`](../index.md#RouteRecordNameGeneric)\> | Parent Route Record where `route` should be appended at | | `route` | [`RouteRecordRaw`](../index.md#RouteRecordRaw) | Route Record to add | #### Returns @@ -53,8 +53,6 @@ Add a new [route record](../index.md#RouteRecordRaw) as the child of an existing ▸ (): `void` -Add a new [route record](../index.md#RouteRecordRaw) as the child of an existing route. - ##### Returns `void` @@ -75,8 +73,6 @@ Add a new [route record](../index.md#RouteRecordRaw) to the router. ▸ (): `void` -Add a new [route record](../index.md#RouteRecordRaw) to the router. - ##### Returns `void` @@ -104,25 +100,10 @@ a function that removes the registered hook ▸ (): `void` -Add a navigation hook that is executed after every navigation. Returns a -function that removes the registered hook. - ##### Returns `void` -a function that removes the registered hook - -**`Example`** - -```js -router.afterEach((to, from, failure) => { - if (isNavigationFailure(failure)) { - console.log('failed navigation', failure) - } -}) -``` - **`Example`** ```js @@ -167,9 +148,6 @@ function that removes the registered guard. ▸ (): `void` -Add a navigation guard that executes before any navigation. Returns a -function that removes the registered guard. - ##### Returns `void` @@ -199,17 +177,10 @@ a function that removes the registered guard ▸ (): `void` -Add a navigation guard that executes before navigation is about to be -resolved. At this state all component have been fetched and other -navigation guards have been successful. Returns a function that removes the -registered guard. - ##### Returns `void` -a function that removes the registered guard - **`Example`** ```js @@ -218,13 +189,17 @@ router.beforeResolve(to => { }) ``` -**`Example`** +___ -```js -router.beforeResolve(to => { - if (to.meta.requiresAuth && !isAuthenticated) return false -}) -``` +### clearRoutes + +▸ **clearRoutes**(): `void` + +Delete all routes from the router matcher. + +#### Returns + +`void` ___ @@ -282,7 +257,7 @@ Checks if a route with a given name exists | Name | Type | Description | | :------ | :------ | :------ | -| `name` | [`RouteRecordName`](../index.md#RouteRecordName) | Name of the route to check | +| `name` | `NonNullable`\<[`RouteRecordNameGeneric`](../index.md#RouteRecordNameGeneric)\> | Name of the route to check | #### Returns @@ -290,6 +265,25 @@ Checks if a route with a given name exists ___ +### install + +▸ **install**(`app`): `void` + +Called automatically by `app.use(router)`. Should not be called manually by +the user. This will trigger the initial navigation when on client side. + +#### Parameters + +| Name | Type | Description | +| :------ | :------ | :------ | +| `app` | `App`\<`any`\> | Application that uses the router | + +#### Returns + +`void` + +___ + ### isReady ▸ **isReady**(): `Promise`\<`void`\> @@ -332,12 +326,6 @@ is required to render a route. ▸ (): `void` -Adds an error handler that is called every time a non caught error happens -during navigation. This includes errors thrown synchronously and -asynchronously, errors returned or passed to `next` in any navigation -guard, and errors occurred when trying to resolve an async component that -is required to render a route. - ##### Returns `void` @@ -355,7 +343,7 @@ stack. | Name | Type | Description | | :------ | :------ | :------ | -| `to` | [`RouteLocationRaw`](../index.md#RouteLocationRaw) | Route location to navigate to | +| `to` | `string` \| [`RouteLocationAsRelativeGeneric`](RouteLocationAsRelativeGeneric.md) \| [`RouteLocationAsPathGeneric`](RouteLocationAsPathGeneric.md) | Route location to navigate to | #### Returns @@ -373,7 +361,7 @@ Remove an existing route by its name. | Name | Type | Description | | :------ | :------ | :------ | -| `name` | [`RouteRecordName`](../index.md#RouteRecordName) | Name of the route to remove | +| `name` | `NonNullable`\<[`RouteRecordNameGeneric`](../index.md#RouteRecordNameGeneric)\> | Name of the route to remove | #### Returns @@ -392,7 +380,7 @@ the history stack. | Name | Type | Description | | :------ | :------ | :------ | -| `to` | [`RouteLocationRaw`](../index.md#RouteLocationRaw) | Route location to navigate to | +| `to` | `string` \| [`RouteLocationAsRelativeGeneric`](RouteLocationAsRelativeGeneric.md) \| [`RouteLocationAsPathGeneric`](RouteLocationAsPathGeneric.md) | Route location to navigate to | #### Returns @@ -402,20 +390,39 @@ ___ ### resolve -▸ **resolve**(`to`, `currentLocation?`): [`RouteLocation`](RouteLocation.md) & \{ `href`: `string` } +▸ **resolve**\<`Name`\>(`to`, `currentLocation?`): [`RouteLocationResolvedGeneric`](RouteLocationResolvedGeneric.md) -Returns the [normalized version](RouteLocation.md) of a +Returns the [normalized version](../index.md#RouteLocation) of a [route location](../index.md#RouteLocationRaw). Also includes an `href` property that includes any existing `base`. By default, the `currentLocation` used is `router.currentRoute` and should only be overridden in advanced use cases. +#### Type parameters + +| Name | Type | +| :------ | :------ | +| `Name` | extends `string` \| `symbol` = `string` \| `symbol` | + #### Parameters | Name | Type | Description | | :------ | :------ | :------ | -| `to` | [`RouteLocationRaw`](../index.md#RouteLocationRaw) | Raw route location to resolve | -| `currentLocation?` | [`RouteLocationNormalizedLoaded`](RouteLocationNormalizedLoaded.md) | Optional current location to resolve against | +| `to` | [`RouteLocationAsRelativeTyped`](RouteLocationAsRelativeTyped.md)\<[`RouteMapGeneric`](../index.md#RouteMapGeneric), `Name`\> | Raw route location to resolve | +| `currentLocation?` | [`RouteLocationNormalizedLoadedGeneric`](RouteLocationNormalizedLoadedGeneric.md) | Optional current location to resolve against | + +#### Returns + +[`RouteLocationResolvedGeneric`](RouteLocationResolvedGeneric.md) + +▸ **resolve**(`to`, `currentLocation?`): [`RouteLocationResolvedGeneric`](RouteLocationResolvedGeneric.md) + +#### Parameters + +| Name | Type | +| :------ | :------ | +| `to` | `string` \| [`RouteLocationAsRelativeGeneric`](RouteLocationAsRelativeGeneric.md) \| [`RouteLocationAsPathGeneric`](RouteLocationAsPathGeneric.md) | +| `currentLocation?` | [`RouteLocationNormalizedLoadedGeneric`](RouteLocationNormalizedLoadedGeneric.md) | #### Returns -[`RouteLocation`](RouteLocation.md) & \{ `href`: `string` } +[`RouteLocationResolvedGeneric`](RouteLocationResolvedGeneric.md) diff --git a/packages/docs/api/interfaces/RouterHistory.md b/packages/docs/api/interfaces/RouterHistory.md index a7fb4b017..8108fd93e 100644 --- a/packages/docs/api/interfaces/RouterHistory.md +++ b/packages/docs/api/interfaces/RouterHistory.md @@ -116,17 +116,10 @@ a callback to remove the listener ▸ (): `void` -Attach a listener to the History implementation that is triggered when the -navigation is triggered from outside (like the Browser back and forward -buttons) or when passing `true` to RouterHistory.back and -RouterHistory.forward - ##### Returns `void` -a callback to remove the listener - ___ ### push diff --git a/packages/docs/api/interfaces/RouterLinkI.md b/packages/docs/api/interfaces/RouterLinkI.md new file mode 100644 index 000000000..2a047e345 --- /dev/null +++ b/packages/docs/api/interfaces/RouterLinkI.md @@ -0,0 +1,56 @@ +--- +editLink: false +--- + +[API Documentation](../index.md) / \_RouterLinkI + +# Interface: \_RouterLinkI + +Typed version of the `RouterLink` component. Its generic defaults to the typed router, so it can be inferred +automatically for JSX. + +## Constructors + +### constructor + +• **new _RouterLinkI**(): `Object` + +#### Returns + +`Object` + +| Name | Type | +| :------ | :------ | +| `$props` | `AllowedComponentProps` & `ComponentCustomProps` & `VNodeProps` & [`RouterLinkProps`](RouterLinkProps.md) | +| `$slots` | \{ `default?`: (`__namedParameters`: \{ `href`: `string` ; `isActive`: `boolean` ; `isExactActive`: `boolean` ; `route`: [`RouteLocationResolvedGeneric`](RouteLocationResolvedGeneric.md) ; `navigate`: (`e?`: `MouseEvent`) => `Promise`\<`void` \| [`NavigationFailure`](NavigationFailure.md)\> }) => `VNode`\<`RendererNode`, `RendererElement`, \{ `[key: string]`: `any`; }\>[] } | +| `$slots.default?` | (`__namedParameters`: \{ `href`: `string` ; `isActive`: `boolean` ; `isExactActive`: `boolean` ; `route`: [`RouteLocationResolvedGeneric`](RouteLocationResolvedGeneric.md) ; `navigate`: (`e?`: `MouseEvent`) => `Promise`\<`void` \| [`NavigationFailure`](NavigationFailure.md)\> }) => `VNode`\<`RendererNode`, `RendererElement`, \{ `[key: string]`: `any`; }\>[] | + +## Properties + +### useLink + +• **useLink**: \(`props`: [`UseLinkOptions`](UseLinkOptions.md)\<`Name`\>) => [`UseLinkReturn`](UseLinkReturn.md)\<`Name`\> + +Access to `useLink()` without depending on using vue-router + +#### Type declaration + +▸ \<`Name`\>(`props`): [`UseLinkReturn`](UseLinkReturn.md)\<`Name`\> + +Access to `useLink()` without depending on using vue-router + +##### Type parameters + +| Name | Type | +| :------ | :------ | +| `Name` | extends `string` \| `symbol` = `string` \| `symbol` | + +##### Parameters + +| Name | Type | +| :------ | :------ | +| `props` | [`UseLinkOptions`](UseLinkOptions.md)\<`Name`\> | + +##### Returns + +[`UseLinkReturn`](UseLinkReturn.md)\<`Name`\> diff --git a/packages/docs/api/interfaces/RouterLinkProps.md b/packages/docs/api/interfaces/RouterLinkProps.md index e8aa8778d..f046e51aa 100644 --- a/packages/docs/api/interfaces/RouterLinkProps.md +++ b/packages/docs/api/interfaces/RouterLinkProps.md @@ -24,7 +24,7 @@ ___ ### ariaCurrentValue -• `Optional` **ariaCurrentValue**: ``"location"`` \| ``"time"`` \| ``"page"`` \| ``"step"`` \| ``"date"`` \| ``"true"`` \| ``"false"`` +• `Optional` **ariaCurrentValue**: ``"time"`` \| ``"location"`` \| ``"page"`` \| ``"step"`` \| ``"date"`` \| ``"true"`` \| ``"false"`` Value passed to the attribute `aria-current` when the link is exact active. @@ -65,7 +65,7 @@ ___ ### to -• **to**: [`RouteLocationRaw`](../index.md#RouteLocationRaw) +• **to**: `string` \| [`RouteLocationAsRelativeGeneric`](RouteLocationAsRelativeGeneric.md) \| [`RouteLocationAsPathGeneric`](RouteLocationAsPathGeneric.md) Route Location the link should navigate to when clicked on. diff --git a/packages/docs/api/interfaces/RouterMatcher.md b/packages/docs/api/interfaces/RouterMatcher.md new file mode 100644 index 000000000..bc18a13d0 --- /dev/null +++ b/packages/docs/api/interfaces/RouterMatcher.md @@ -0,0 +1,145 @@ +--- +editLink: false +--- + +[API Documentation](../index.md) / RouterMatcher + +# Interface: RouterMatcher + +Internal RouterMatcher + +## Properties + +### addRoute + +• **addRoute**: (`record`: [`RouteRecordRaw`](../index.md#RouteRecordRaw), `parent?`: `RouteRecordMatcher`) => () => `void` + +#### Type declaration + +▸ (`record`, `parent?`): () => `void` + +##### Parameters + +| Name | Type | +| :------ | :------ | +| `record` | [`RouteRecordRaw`](../index.md#RouteRecordRaw) | +| `parent?` | `RouteRecordMatcher` | + +##### Returns + +`fn` + +▸ (): `void` + +##### Returns + +`void` + +___ + +### clearRoutes + +• **clearRoutes**: () => `void` + +#### Type declaration + +▸ (): `void` + +##### Returns + +`void` + +___ + +### getRecordMatcher + +• **getRecordMatcher**: (`name`: `NonNullable`\<[`RouteRecordNameGeneric`](../index.md#RouteRecordNameGeneric)\>) => `undefined` \| `RouteRecordMatcher` + +#### Type declaration + +▸ (`name`): `undefined` \| `RouteRecordMatcher` + +##### Parameters + +| Name | Type | +| :------ | :------ | +| `name` | `NonNullable`\<[`RouteRecordNameGeneric`](../index.md#RouteRecordNameGeneric)\> | + +##### Returns + +`undefined` \| `RouteRecordMatcher` + +___ + +### getRoutes + +• **getRoutes**: () => `RouteRecordMatcher`[] + +#### Type declaration + +▸ (): `RouteRecordMatcher`[] + +##### Returns + +`RouteRecordMatcher`[] + +___ + +### resolve + +• **resolve**: (`location`: `MatcherLocationRaw`, `currentLocation`: [`MatcherLocation`](MatcherLocation.md)) => [`MatcherLocation`](MatcherLocation.md) + +Resolves a location. Gives access to the route record that corresponds to the actual path as well as filling the corresponding params objects + +**`Param`** + +MatcherLocationRaw to resolve to a url + +**`Param`** + +MatcherLocation of the current location + +#### Type declaration + +▸ (`location`, `currentLocation`): [`MatcherLocation`](MatcherLocation.md) + +Resolves a location. Gives access to the route record that corresponds to the actual path as well as filling the corresponding params objects + +##### Parameters + +| Name | Type | Description | +| :------ | :------ | :------ | +| `location` | `MatcherLocationRaw` | MatcherLocationRaw to resolve to a url | +| `currentLocation` | [`MatcherLocation`](MatcherLocation.md) | MatcherLocation of the current location | + +##### Returns + +[`MatcherLocation`](MatcherLocation.md) + +## Methods + +### removeRoute + +▸ **removeRoute**(`matcher`): `void` + +#### Parameters + +| Name | Type | +| :------ | :------ | +| `matcher` | `RouteRecordMatcher` | + +#### Returns + +`void` + +▸ **removeRoute**(`name`): `void` + +#### Parameters + +| Name | Type | +| :------ | :------ | +| `name` | `NonNullable`\<[`RouteRecordNameGeneric`](../index.md#RouteRecordNameGeneric)\> | + +#### Returns + +`void` diff --git a/packages/docs/api/interfaces/RouterOptions.md b/packages/docs/api/interfaces/RouterOptions.md index 039498275..f431256df 100644 --- a/packages/docs/api/interfaces/RouterOptions.md +++ b/packages/docs/api/interfaces/RouterOptions.md @@ -75,6 +75,23 @@ ___ • `Optional` **parseQuery**: (`search`: `string`) => [`LocationQuery`](../index.md#LocationQuery) +Custom implementation to parse a query. See its counterpart, +[RouterOptions.stringifyQuery](RouterOptions.md#stringifyQuery). + +**`Example`** + +Let's say you want to use the [qs package](https://github.com/ljharb/qs) +to parse queries, you can provide both `parseQuery` and `stringifyQuery`: +```js +import qs from 'qs' + +createRouter({ + // other options... + parseQuery: qs.parse, + stringifyQuery: qs.stringify, +}) +``` + #### Type declaration ▸ (`search`): [`LocationQuery`](../index.md#LocationQuery) @@ -170,6 +187,9 @@ ___ • `Optional` **stringifyQuery**: (`query`: [`LocationQueryRaw`](../index.md#LocationQueryRaw)) => `string` +Custom implementation to stringify a query object. Should not prepend a leading `?`. +[parseQuery](RouterOptions.md#parseQuery) counterpart to handle query parsing. + #### Type declaration ▸ (`query`): `string` diff --git a/packages/docs/api/interfaces/RouterScrollBehavior.md b/packages/docs/api/interfaces/RouterScrollBehavior.md index 049a72503..802e5e5f7 100644 --- a/packages/docs/api/interfaces/RouterScrollBehavior.md +++ b/packages/docs/api/interfaces/RouterScrollBehavior.md @@ -18,8 +18,8 @@ Type of the `scrollBehavior` option that can be passed to `createRouter`. | Name | Type | Description | | :------ | :------ | :------ | -| `to` | [`RouteLocationNormalized`](RouteLocationNormalized.md) | Route location where we are navigating to | -| `from` | [`RouteLocationNormalizedLoaded`](RouteLocationNormalizedLoaded.md) | Route location where we are navigating from | +| `to` | [`RouteLocationNormalizedGeneric`](RouteLocationNormalizedGeneric.md) | Route location where we are navigating to | +| `from` | [`RouteLocationNormalizedLoadedGeneric`](RouteLocationNormalizedLoadedGeneric.md) | Route location where we are navigating from | | `savedPosition` | ``null`` \| `_ScrollPositionNormalized` | saved position if it exists, `null` otherwise | #### Returns diff --git a/packages/docs/api/interfaces/RouterViewProps.md b/packages/docs/api/interfaces/RouterViewProps.md index 30fc957d2..af5477d4e 100644 --- a/packages/docs/api/interfaces/RouterViewProps.md +++ b/packages/docs/api/interfaces/RouterViewProps.md @@ -16,4 +16,4 @@ ___ ### route -• `Optional` **route**: [`RouteLocationNormalized`](RouteLocationNormalized.md) +• `Optional` **route**: [`RouteLocationNormalizedGeneric`](RouteLocationNormalizedGeneric.md) diff --git a/packages/docs/api/interfaces/TypesConfig.md b/packages/docs/api/interfaces/TypesConfig.md new file mode 100644 index 000000000..09961cd04 --- /dev/null +++ b/packages/docs/api/interfaces/TypesConfig.md @@ -0,0 +1,17 @@ +--- +editLink: false +--- + +[API Documentation](../index.md) / TypesConfig + +# Interface: TypesConfig + +Allows customizing existing types of the router that are used globally like `$router`, ``, etc. **ONLY FOR INTERNAL USAGE**. + +- `$router` - the router instance +- `$route` - the current route location +- `beforeRouteEnter` - Page component option +- `beforeRouteUpdate` - Page component option +- `beforeRouteLeave` - Page component option +- `RouterLink` - RouterLink Component +- `RouterView` - RouterView Component diff --git a/packages/docs/api/interfaces/UseLinkOptions.md b/packages/docs/api/interfaces/UseLinkOptions.md new file mode 100644 index 000000000..3db657f34 --- /dev/null +++ b/packages/docs/api/interfaces/UseLinkOptions.md @@ -0,0 +1,27 @@ +--- +editLink: false +--- + +[API Documentation](../index.md) / UseLinkOptions + +# Interface: UseLinkOptions\ + +Options passed to [useLink](../index.md#useLink). + +## Type parameters + +| Name | Type | +| :------ | :------ | +| `Name` | extends keyof [`RouteMap`](../index.md#RouteMap) = keyof [`RouteMap`](../index.md#RouteMap) | + +## Properties + +### replace + +• `Optional` **replace**: `MaybeRef`\<`undefined` \| `boolean`\> + +___ + +### to + +• **to**: `MaybeRef`\<`string` \| [`RouteLocationAsRelativeGeneric`](RouteLocationAsRelativeGeneric.md) \| [`RouteLocationAsPathGeneric`](RouteLocationAsPathGeneric.md) \| [`RouteLocationAsRelativeTyped`](RouteLocationAsRelativeTyped.md)\<[`RouteMapGeneric`](../index.md#RouteMapGeneric), `Name`\>\> diff --git a/packages/docs/api/interfaces/UseLinkReturn.md b/packages/docs/api/interfaces/UseLinkReturn.md new file mode 100644 index 000000000..533fd8bd1 --- /dev/null +++ b/packages/docs/api/interfaces/UseLinkReturn.md @@ -0,0 +1,55 @@ +--- +editLink: false +--- + +[API Documentation](../index.md) / UseLinkReturn + +# Interface: UseLinkReturn\ + +Return type of [useLink](../index.md#useLink). + +## Type parameters + +| Name | Type | +| :------ | :------ | +| `Name` | extends keyof [`RouteMap`](../index.md#RouteMap) = keyof [`RouteMap`](../index.md#RouteMap) | + +## Properties + +### href + +• **href**: `ComputedRef`\<`string`\> + +___ + +### isActive + +• **isActive**: `ComputedRef`\<`boolean`\> + +___ + +### isExactActive + +• **isExactActive**: `ComputedRef`\<`boolean`\> + +___ + +### route + +• **route**: `ComputedRef`\<[`RouteLocationResolvedGeneric`](RouteLocationResolvedGeneric.md)\> + +## Methods + +### navigate + +▸ **navigate**(`e?`): `Promise`\<`void` \| [`NavigationFailure`](NavigationFailure.md)\> + +#### Parameters + +| Name | Type | +| :------ | :------ | +| `e?` | `MouseEvent` | + +#### Returns + +`Promise`\<`void` \| [`NavigationFailure`](NavigationFailure.md)\> diff --git a/packages/docs/compare-to-translate.mjs b/packages/docs/compare-to-translate.mjs deleted file mode 100644 index 7e92d45d6..000000000 --- a/packages/docs/compare-to-translate.mjs +++ /dev/null @@ -1,45 +0,0 @@ -// @ts-check -import { readFile } from 'fs/promises' -import simpleGit from 'simple-git' - -// The path to the translation status file. -const STATUS_FILE_PATH = './.vitepress/translation-status.json' - -const usage = ` -Usage: pnpm run docs:compare-to-translate [] - locale: The target locale to compare. - commit: The target commit to compare. It could be a branch, a tag, or a hash. Default to 'main'.` - -async function getLocaleHash (lang) { - try { - const content = await readFile(STATUS_FILE_PATH, 'utf8') - const data = JSON.parse(content) - return data[lang]?.hash - } catch (err) { - console.log('No previous status file. Will create a new one.') - } -} - -async function main() { - if (process.argv.find(arg => arg === '--help' || arg === '-h')) { - console.log(usage) - return - } - - const locale = process.argv[2] - const commit = process.argv[3] || 'main' - - const hash = await getLocaleHash(locale) - if (hash) { - console.log(`The last checkpoint of docs(${locale}) is "${hash}".\n`) - const git = simpleGit() - const result = await git.diff([`${hash}..${commit}`, '.']) - console.log(result) - console.log(`\nAfter finishing the translation, you can run\n"pnpm run docs:translation-status ${locale} ${hash}"\nor\n"pnpm run docs:translation-status ${locale}${commit !== 'main' ? ' ' + commit : ''}"\nto update the translation status file.`) - } else { - console.log(`No docs(${locale}) checkpoint found.\n`) - console.log(usage) - } -} - -main() diff --git a/packages/docs/generate-translation-status.mjs b/packages/docs/generate-translation-status.mjs deleted file mode 100644 index 1a165e8c1..000000000 --- a/packages/docs/generate-translation-status.mjs +++ /dev/null @@ -1,60 +0,0 @@ -// @ts-check -import { writeFile, readFile } from 'fs/promises' -import simpleGit from 'simple-git' - -// The path to the translation status file. -const STATUS_FILE_PATH = './.vitepress/translation-status.json' - -const usage = ` -Usage: pnpm run docs:translation-status [] - locale: The target locale to update. - commit: The target commit to update. It could be a branch, a tag, or a hash. Default to 'main'.` - -async function getCommitInfo (commit) { - try { - const git = simpleGit() - const log = await git.log([commit, '-n', '1']) - const { hash, date } = log.latest - return { hash, date: new Date(date).toISOString().substring(0, 10) } - } catch (err) { - return { hash: '', date: '' } - } -} - -async function writeLangMap (lang, hash, date) { - const data = {} - try { - const previousContent = await readFile(STATUS_FILE_PATH, 'utf8') - const previousJson = JSON.parse(previousContent) - Object.assign(data, previousJson) - } - catch (err) { - console.log('No previous status file. Will create a new one.') - } - data[lang] = { - hash, - date, - } - await writeFile(STATUS_FILE_PATH, JSON.stringify(data, null, 2)) -} - -async function main() { - if (process.argv.find(arg => arg === '--help' || arg === '-h')) { - console.log(usage) - return - } - - const locale = process.argv[2] - const commit = process.argv[3] || 'main' - - const { hash, date } = await getCommitInfo(commit) - if (!hash) { - console.log(`❌ No commit found for "${commit}".`) - return - } else { - await writeLangMap(locale, hash, date) - console.log(`✅ Updated ${locale} to "${hash}" (${date})`) - } -} - -main() diff --git a/packages/docs/guide/advanced/composition-api.md b/packages/docs/guide/advanced/composition-api.md index 3e9213f78..26e84d1d8 100644 --- a/packages/docs/guide/advanced/composition-api.md +++ b/packages/docs/guide/advanced/composition-api.md @@ -2,90 +2,84 @@ -The introduction of `setup` and Vue's [Composition API](https://vuejs.org/guide/extras/composition-api-faq.html), open up new possibilities but to be able to get the full potential out of Vue Router, we will need to use a few new functions to replace access to `this` and in-component navigation guards. +The introduction of Vue's [Composition API](https://vuejs.org/guide/extras/composition-api-faq.html) opened up new possibilities, but to be able to get the full potential out of Vue Router, we will need to use a few new functions to replace access to `this` and in-component navigation guards. ## Accessing the Router and current Route inside `setup` -Because we don't have access to `this` inside of `setup`, we cannot directly access `this.$router` or `this.$route` anymore. Instead we use the `useRouter` and `useRoute` functions: +Because we don't have access to `this` inside of `setup`, we cannot directly access `this.$router` or `this.$route`. Instead, we use the `useRouter` and `useRoute` composables: -```js +```vue + ``` -The `route` object is a reactive object, so any of its properties can be watched and you should **avoid watching the whole `route`** object. In most scenarios, you should directly watch the param you are expecting to change +The `route` object is a reactive object. In most scenarios, you should **avoid watching the whole `route`** object. Instead, you can directly watch the properties you are expecting to change: -```js +```vue + ``` -Note we still have access to `$router` and `$route` in templates, so there is no need to return `router` or `route` inside of `setup`. +Note we still have access to `$router` and `$route` in templates, so there's no need to use `useRouter` or `useRoute` if we only need those objects in the template. ## Navigation Guards -While you can still use in-component navigation guards with a `setup` function, Vue Router exposes update and leave guards as Composition API functions: +Vue Router exposes update and leave guards as Composition API functions: -```js +```vue + ``` Composition API guards can also be used in any component rendered by ``, they don't have to be used directly on the route component like in-component guards. @@ -94,40 +88,34 @@ Composition API guards can also be used in any component rendered by ` import { RouterLink, useLink } from 'vue-router' import { computed } from 'vue' -export default { - name: 'AppLink', - - props: { - // add @ts-ignore if using TypeScript - ...RouterLink.props, - inactiveClass: String, - }, - - setup(props) { - const { - // the resolved route object - route, - // the href to use in a link - href, - // boolean ref indicating if the link is active - isActive, - // boolean ref indicating if the link is exactly active - isExactActive, - // function to navigate to the link - navigate - } = useLink(props) - - const isExternalLink = computed( - () => typeof props.to === 'string' && props.to.startsWith('http') - ) - - return { isExternalLink, href, navigate, isActive } - }, -} +const props = defineProps({ + // add @ts-ignore if using TypeScript + ...RouterLink.props, + inactiveClass: String, +}) + +const { + // the resolved route object + route, + // the href to use in a link + href, + // boolean ref indicating if the link is active + isActive, + // boolean ref indicating if the link is exactly active + isExactActive, + // function to navigate to the link + navigate +} = useLink(props) + +const isExternalLink = computed( + () => typeof props.to === 'string' && props.to.startsWith('http') +) + ``` Note that the RouterLink's `v-slot` gives access to the same properties as the `useLink` composable. diff --git a/packages/docs/guide/advanced/data-fetching.md b/packages/docs/guide/advanced/data-fetching.md index e0725abeb..c6fd1bfb4 100644 --- a/packages/docs/guide/advanced/data-fetching.md +++ b/packages/docs/guide/advanced/data-fetching.md @@ -10,11 +10,13 @@ Technically, both are valid choices - it ultimately depends on the user experien ## Fetching After Navigation -When using this approach, we navigate and render the incoming component immediately, and fetch data in the component's `created` hook. It gives us the opportunity to display a loading state while the data is being fetched over the network, and we can also handle loading differently for each view. +When using this approach, we navigate and render the incoming component immediately, and fetch data in the component itself. It gives us the opportunity to display a loading state while the data is being fetched over the network, and we can also handle loading differently for each view. -Let's assume we have a `Post` component that needs to fetch the data for a post based on `$route.params.id`: +Let's assume we have a `Post` component that needs to fetch the data for a post based on `route.params.id`: -```html +::: code-group + +```vue [Composition API] + + ``` -```js +```vue [Options API] + + + ``` +::: + ## Fetching Before Navigation -With this approach we fetch the data before actually navigating to the new -route. We can perform the data fetching in the `beforeRouteEnter` guard in the incoming component, and only call `next` when the fetch is complete. The callback passed to `next` will be called **after the component is mounted**: +With this approach we fetch the data before actually navigating to the new route. We can perform the data fetching in the `beforeRouteEnter` guard in the incoming component, and only call `next` when the fetch is complete. The callback passed to `next` will be called **after the component is mounted**: ```js export default { @@ -81,29 +128,28 @@ export default { error: null, } }, - beforeRouteEnter(to, from, next) { - getPost(to.params.id, (err, post) => { - // `setData` is a method defined below - next(vm => vm.setData(err, post)) - }) + async beforeRouteEnter(to, from, next) { + try { + const post = await getPost(to.params.id) + // `setPost` is a method defined below + next(vm => vm.setPost(post)) + } catch (err) { + // `setError` is a method defined below + next(vm => vm.setError(err)) + } }, // when route changes and this component is already rendered, // the logic will be slightly different. - async beforeRouteUpdate(to, from) { + beforeRouteUpdate(to, from) { this.post = null - try { - this.post = await getPost(to.params.id) - } catch (error) { - this.error = error.toString() - } + getPost(to.params.id).then(this.setPost).catch(this.setError) }, methods: { - setData(error, post) { - if (error) { - this.error = error - } else { - this.post = post - } + setPost(post) { + this.post = post + }, + setError(err) { + this.error = err.toString() } } } diff --git a/packages/docs/guide/advanced/dynamic-routing.md b/packages/docs/guide/advanced/dynamic-routing.md index a2ad81a79..5488b2fa3 100644 --- a/packages/docs/guide/advanced/dynamic-routing.md +++ b/packages/docs/guide/advanced/dynamic-routing.md @@ -5,7 +5,7 @@ title="Learn how to add routes at runtime" /> -Adding routes to your router is usually done via the `routes` option but in some situations, you might want to add or remove routes while the application is already running. Application with extensible interfaces like [Vue CLI UI](https://cli.vuejs.org/dev-guide/ui-api.html) can use this to make the application grow. +Adding routes to your router is usually done via the `routes` option but in some situations, you might want to add or remove routes while the application is already running. Applications with extensible interfaces like [Vue CLI UI](https://cli.vuejs.org/dev-guide/ui-api.html) can use this to make the application grow. ## Adding routes @@ -20,17 +20,17 @@ const router = createRouter({ }) ``` -Going to any page, `/about`, `/store`, or `/3-tricks-to-improve-your-routing-code` ends up rendering the `Article` component. If we are on `/about` and we add a new route: +Going to any page like `/about`, `/store`, or `/3-tricks-to-improve-your-routing-code` ends up rendering the `Article` component. If we are on `/about` and we add a new route: ```js router.addRoute({ path: '/about', component: About }) ``` -The page will still show the `Article` component, we need to manually call `router.replace()` to change the current location and overwrite where we were (instead of pushing a new entry, ending up in the same location twice in our history): +The page will still show the `Article` component. We need to manually call `router.replace()` to change the current location and overwrite where we were (instead of pushing a new entry, ending up in the same location twice in our history): ```js router.addRoute({ path: '/about', component: About }) -// we could also use this.$route or route = useRoute() (inside a setup) +// we could also use this.$route or useRoute() router.replace(router.currentRoute.value.fullPath) ``` @@ -89,7 +89,7 @@ Whenever a route is removed, **all of its aliases and children** are removed wit ## Adding nested routes -To add nested routes to an existing route, you can pass the _name_ of the route as its first parameter to `router.addRoute()`, this will effectively add the route as if it was added through `children`: +To add nested routes to an existing route, you can pass the _name_ of the route as its first parameter to `router.addRoute()`. This will effectively add the route as if it was added through `children`: ```js router.addRoute({ name: 'admin', path: '/admin', component: Admin }) @@ -111,5 +111,5 @@ router.addRoute({ Vue Router gives you two functions to look at existing routes: -- [`router.hasRoute()`](/api/interfaces/Router.md#hasRoute): check if a route exists +- [`router.hasRoute()`](/api/interfaces/Router.md#hasRoute): check if a route exists. - [`router.getRoutes()`](/api/interfaces/Router.md#getRoutes): get an array with all the route records. diff --git a/packages/docs/guide/advanced/extending-router-link.md b/packages/docs/guide/advanced/extending-router-link.md index 6b4ff25c4..5102b9ad5 100644 --- a/packages/docs/guide/advanced/extending-router-link.md +++ b/packages/docs/guide/advanced/extending-router-link.md @@ -9,7 +9,28 @@ The RouterLink component exposes enough `props` to suffice most basic applicatio Let's extend RouterLink to handle external links as well and adding a custom `inactive-class` in an `AppLink.vue` file: -```vue +::: code-group + +```vue [Composition API] + + +``` +```vue [Options API] + + ``` +::: + If you prefer using a render function or create `computed` properties, you can use the `useLink` from the [Composition API](./composition-api.md): ```js diff --git a/packages/docs/guide/advanced/meta.md b/packages/docs/guide/advanced/meta.md index 7c5f045d8..321158ff6 100644 --- a/packages/docs/guide/advanced/meta.md +++ b/packages/docs/guide/advanced/meta.md @@ -38,7 +38,7 @@ First, each route object in the `routes` configuration is called a **route recor For example, with the above route config, the URL `/posts/new` will match both the parent route record (`path: '/posts'`) and the child route record (`path: 'new'`). -All route records matched by a route are exposed on the `$route` object (and also route objects in navigation guards) as the `$route.matched` Array. We could loop through that array to check all `meta` fields, but Vue Router also provides you a `$route.meta` that is a non-recursive merge of **all `meta`** fields from parent to child. Meaning you can simply write +All route records matched by a route are exposed on the `route` object (and also route objects in navigation guards) as the `route.matched` Array. We could loop through that array to check all `meta` fields, but Vue Router also provides you a `route.meta` that is a non-recursive merge of **all `meta`** fields from parent to child. Meaning you can simply write: ```js router.beforeEach((to, from) => { diff --git a/packages/docs/guide/advanced/navigation-guards.md b/packages/docs/guide/advanced/navigation-guards.md index 1d0067f60..12975df37 100644 --- a/packages/docs/guide/advanced/navigation-guards.md +++ b/packages/docs/guide/advanced/navigation-guards.md @@ -25,8 +25,8 @@ Global before guards are called in creation order, whenever a navigation is trig Every guard function receives two arguments: -- **`to`**: the target route location [in a normalized format](../../api/interfaces/RouteLocationNormalized.md) being navigated to. -- **`from`**: the current route location [in a normalized format](../../api/interfaces/RouteLocationNormalized.md) being navigated away from. +- **`to`**: the target route location [in a normalized format](../../api/#RouteLocationNormalized) being navigated to. +- **`from`**: the current route location [in a normalized format](../../api/#RouteLocationNormalized) being navigated away from. And can optionally return any of the following values: @@ -197,13 +197,34 @@ const routes = [ ] ``` -Note it is possible to achieve a similar behavior by using [route meta fields](./meta.md) and global navigation guards. +When working with [nested routes](../essentials/nested-routes), both parent and child routes can use `beforeEnter`. When placed on a parent route, it won't be triggered when moving between children with that same parent. For example: + +```js +const routes = [ + { + path: '/user', + beforeEnter() { + // ... + }, + children: [ + { path: 'list', component: UserList }, + { path: 'details', component: UserDetails }, + ], + }, +] +``` + +The `beforeEnter` in the example above won't be called when moving between `/user/list` and `/user/details`, as they share the same parent. If we put the `beforeEnter` guard directly on the `details` route instead, that would be called when moving between those two routes. + +::: tip +It is possible to achieve similar behavior to per-route guards by using [route meta fields](./meta) and global navigation guards. +::: ## In-Component Guards Finally, you can directly define route navigation guards inside route components (the ones passed to the router configuration) -### Using the options API +### Using the Options API You can add the following options to route components: @@ -211,9 +232,9 @@ You can add the following options to route components: - `beforeRouteUpdate` - `beforeRouteLeave` -```js -const UserDetails = { - template: `...`, +```vue + ``` The `beforeRouteEnter` guard does **NOT** have access to `this`, because the guard is called before the navigation is confirmed, thus the new entering component has not even been created yet. @@ -262,9 +284,9 @@ beforeRouteLeave (to, from) { } ``` -### Using the composition API +### Using the Composition API -If you are writing your component using the [composition API and a `setup` function](https://vuejs.org/api/composition-api-setup.html), you can add update and leave guards through `onBeforeRouteUpdate` and `onBeforeRouteLeave` respectively. Please refer to the [Composition API section](./composition-api.md#navigation-guards) for more details. +If you are writing your component using the Composition API, you can add update and leave guards through `onBeforeRouteUpdate` and `onBeforeRouteLeave` respectively. Please refer to the [Composition API section](./composition-api.md#navigation-guards) for more details. ## The Full Navigation Resolution Flow diff --git a/packages/docs/guide/advanced/typed-routes.md b/packages/docs/guide/advanced/typed-routes.md index 55fd7044e..5863b94ae 100644 --- a/packages/docs/guide/advanced/typed-routes.md +++ b/packages/docs/guide/advanced/typed-routes.md @@ -1,10 +1,62 @@ -# Typed Routes (v4.1.0+) +# Typed Routes -::: danger ‼️ Experimental feature +![RouterLink to autocomplete](https://user-images.githubusercontent.com/664177/176442066-c4e7fa31-4f06-4690-a49f-ed0fd880dfca.png) -Starting from v4.1.0, we are introducing a new feature called Typed Routes. This **experimental** feature is enabled through a Vite/webpack/Rollup plugin. +It's possible to configure the router to have a _map_ of typed routes. While this can be done manually, it is recommended to use the [unplugin-vue-router](https://github.com/posva/unplugin-vue-router) plugin to generate the routes and the types automatically. -![RouterLink to autocomplete](https://user-images.githubusercontent.com/664177/176442066-c4e7fa31-4f06-4690-a49f-ed0fd880dfca.png) +## Manual Configuration + +Here is an example of how to manually configure typed routes: + +```ts +// import the `RouteRecordInfo` type from vue-router to type your routes +import type { RouteRecordInfo } from 'vue-router' + +// Define an interface of routes +export interface RouteNamedMap { + // each key is a name + home: RouteRecordInfo< + // here we have the same name + 'home', + // this is the path, it will appear in autocompletion + '/', + // these are the raw params. In this case, there are no params allowed + Record, + // these are the normalized params + Record + > + // repeat for each route.. + // Note you can name them whatever you want + 'named-param': RouteRecordInfo< + 'named-param', + '/:name', + { name: string | number }, // raw value + { name: string } // normalized value + > + 'article-details': RouteRecordInfo< + 'article-details', + '/articles/:id+', + { id: Array }, + { id: string[] } + > + 'not-found': RouteRecordInfo< + 'not-found', + '/:path(.*)', + { path: string }, + { path: string } + > +} + +// Last, you will need to augment the Vue Router types with this map of routes +declare module 'vue-router' { + interface TypesConfig { + RouteNamedMap: RouteNamedMap + } +} +``` + +::: tip + +This is indeed tedious and error-prone. That's why it's recommended to use [unplugin-vue-router](https://github.com/posva/unplugin-vue-router) to generate the routes and the types automatically. -[Check the v4.1 release notes](https://github.com/vuejs/router/releases/tag/v4.1.0) for more information about this feature. -[Check out the plugin](https://github.com/posva/unplugin-vue-router) GitHub repository for installation instructions and documentation. +::: diff --git a/packages/docs/guide/essentials/active-links.md b/packages/docs/guide/essentials/active-links.md new file mode 100644 index 000000000..3c5f23baa --- /dev/null +++ b/packages/docs/guide/essentials/active-links.md @@ -0,0 +1,78 @@ +# Active links + +It's common for applications to have a navigation component that renders a list of RouterLink components. Within that list, we might want to style links to the currently active route differently from the others. + +The RouterLink component adds two CSS classes to active links, `router-link-active` and `router-link-exact-active`. To understand the difference between them, we first need to consider how Vue Router decides that a link is _active_. + +## When are links active? + +A RouterLink is considered to be **_active_** if: + +1. It matches the same route record (i.e. configured route) as the current location. +2. It has the same values for the `params` as the current location. + +If you're using [nested routes](./nested-routes), any links to ancestor routes will also be considered active if the relevant `params` match. + +Other route properties, such as the [`query`](../../api/interfaces/RouteLocationBase.html#query), are not taken into account. + +The path doesn't necessarily need to be a perfect match. For example, using an [`alias`](./redirect-and-alias#Alias) would still be considered a match, so long as it resolves to the same route record and `params`. + +If a route has a [`redirect`](./redirect-and-alias#Redirect), it won't be followed when checking whether a link is active. + +## Exact active links + +An **_exact_** match does not include ancestor routes. + +Let's imagine we have the following routes: + +```js +const routes = [ + { + path: '/user/:username', + component: User, + children: [ + { + path: 'role/:roleId', + component: Role, + }, + ], + }, +] +``` + +Then consider these two links: + +```vue-html + + User + + + Role + +``` + +If the current location path is `/user/erina/role/admin` then these would both be considered _active_, so the class `router-link-active` would be applied to both links. But only the second link would be considered _exact_, so only that second link would have the class `router-link-exact-active`. + +## Configuring the classes + +The RouterLink component has two props, `activeClass` and `exactActiveClass`, that can be used to change the names of the classes that are applied: + +```vue-html + +``` + +The default class names can also be changed globally by passing the `linkActiveClass` and `linkExactActiveClass` options to `createRouter()`: + +```js +const router = createRouter({ + linkActiveClass: 'border-indigo-500', + linkExactActiveClass: 'border-indigo-700', + // ... +}) +``` + +See [Extending RouterLink](../advanced/extending-router-link) for more advanced customization techniques using the `v-slot` API. diff --git a/packages/docs/guide/essentials/dynamic-matching.md b/packages/docs/guide/essentials/dynamic-matching.md index f74ab649d..9c9fd0b94 100644 --- a/packages/docs/guide/essentials/dynamic-matching.md +++ b/packages/docs/guide/essentials/dynamic-matching.md @@ -8,9 +8,7 @@ Very often we will need to map routes with the given pattern to the same component. For example, we may have a `User` component which should be rendered for all users but with different user IDs. In Vue Router we can use a dynamic segment in the path to achieve that, we call that a _param_: ```js -const User = { - template: '
User
', -} +import User from './User.vue' // these are passed to `createRouter` const routes = [ @@ -21,22 +19,25 @@ const routes = [ Now URLs like `/users/johnny` and `/users/jolyne` will both map to the same route. -A _param_ is denoted by a colon `:`. When a route is matched, the value of its _params_ will be exposed as `this.$route.params` in every component. Therefore, we can render the current user ID by updating `User`'s template to this: +A _param_ is denoted by a colon `:`. When a route is matched, the value of its _params_ will be exposed as `route.params` in every component. Therefore, we can render the current user ID by updating `User`'s template to this: -```js -const User = { - template: '
User {{ $route.params.id }}
', -} +```vue + ``` -You can have multiple _params_ in the same route, and they will map to corresponding fields on `$route.params`. Examples: +You can have multiple _params_ in the same route, and they will map to corresponding fields on `route.params`. Examples: -| pattern | matched path | \$route.params | +| pattern | matched path | route.params | | ------------------------------ | ------------------------ | ---------------------------------------- | | /users/:username | /users/eduardo | `{ username: 'eduardo' }` | | /users/:username/posts/:postId | /users/eduardo/posts/123 | `{ username: 'eduardo', postId: '123' }` | -In addition to `$route.params`, the `$route` object also exposes other useful information such as `$route.query` (if there is a query in the URL), `$route.hash`, etc. You can check out the full details in the [API Reference](../../api/interfaces/RouteLocationNormalized.md). +In addition to `route.params`, the `route` object also exposes other useful information such as `route.query` (if there is a query in the URL), `route.hash`, etc. You can check out the full details in the [API Reference](../../api/#RouteLocationNormalized). A working demo of this example can be found [here](https://codesandbox.io/s/route-params-vue-router-examples-mlb14?from-embed&initialpath=%2Fusers%2Feduardo%2Fposts%2F1). @@ -57,34 +58,73 @@ A working demo of this example can be found [here](https://codesandbox.io/s/rout One thing to note when using routes with params is that when the user navigates from `/users/johnny` to `/users/jolyne`, **the same component instance will be reused**. Since both routes render the same component, this is more efficient than destroying the old instance and then creating a new one. **However, this also means that the lifecycle hooks of the component will not be called**. -To react to params changes in the same component, you can simply watch anything on the `$route` object, in this scenario, the `$route.params`: +To react to params changes in the same component, you can simply watch anything on the `route` object, in this scenario, the `route.params`: -```js -const User = { - template: '...', +::: code-group + +```vue [Composition API] + +``` + +```vue [Options API] + ``` -Or, use the `beforeRouteUpdate` [navigation guard](../advanced/navigation-guards.md), which also allows to cancel the navigation: +::: -```js -const User = { - template: '...', +Or, use the `beforeRouteUpdate` [navigation guard](../advanced/navigation-guards.md), which also allows you to cancel the navigation: + +::: code-group + +```vue [Composition API] + +``` + +```vue [Options API] + ``` +::: + ## Catch all / 404 Not found Route -Alongside the `path`, you can provide a `name` to any route. This has the following advantages: - -- No hardcoded URLs -- Automatic encoding/decoding of `params` -- Prevents you from having a typo in the url -- Bypassing path ranking (e.g. to display a ) +When creating a route, we can optionally give the route a `name`: ```js const routes = [ { path: '/user/:username', - name: 'user', + name: 'profile', // [!code highlight] component: User } ] ``` -To link to a named route, you can pass an object to the `router-link` component's `to` prop: +We can then use the `name` instead of the `path` when passing the `to` prop to ``: ```vue-html - - User + + User profile ``` -This is the exact same object used programmatically with `router.push()`: +The example above would create a link to `/user/erina`. -```js -router.push({ name: 'user', params: { username: 'erina' } }) -``` +- [See it in the Playground](https://play.vuejs.org/#eNqtVVtP2zAU/itWNqlFauNNIB6iUMEQEps0NjH2tOzBtKY1JLZlO6VTlP++4+PcelnFwyRofe7fubaKCiZk/GyjJBKFVsaRiswNZ45faU1q8mRUQUbrko8yuaPwlRfK/LkV1sHXpGHeq9JxMzScGmT19t5xkMaUaR1vOb9VBe+kntgWXz2Cs06O1LbCTwvRW7knGnEm50paRwIYcrEFd1xlkpBVyCQ5lN74ZOJV0Nom5JcnCFRCM7dKyIiOJkSygsNzBZiBmivAI7l0SUipRvuhCfPge7uWHBiGZPctS0iLJv7T2/YutFFPIt+JjgUJPn7DZ32CtWg7PIZ/4BASg7txKE6gC1VKNx69gw6NTqJJ1HQK5iR1vNA52M+8Yrr6OLuD+AuCtbQpBQYK9Oy6NAZAhLI1KKuKvEc69jSp65Tqw/oh3V7f00P9MsdveOWiecE75DDNhXwhiVMXWVRttYbUWdRpE2xOZ0sHxq1v2jl/a5jQyZ042Mv/HKjvt2aGFTCXFWmnAsTcCMkAxw4SHIjG9E2AUtpUusWyFvyVUGCltBsFmJB2W/dHZCHWswdYLwJ/XiulnrNr323zcQeodthDuAHTgmm4aEqCH1zsrBHYLIISheyyqD9Nnp1FK+e0TSgtpX5ZxrBBtNe4PItP4w8Q07oBN+a2mD4a9erPzDN4bzY1iy5BiS742imV2ynT4l8h9hQvz+Pz+COU/pGCdyrkgm/Qt3ddw/5Cms7CLXsSy50k/dJDT8037QTcuq1kWZ6r1y/Ic6bkHdD5is9fDvCf7SZA/m44ZLfmg+QcM0vugvjmxx3fwLsTFmpRwlwdE95zq/LSYwxqn0q5ANgDPUT7GXsm5PLB3mwcl7ZNygPFaqA+NvL6SOo93NP4bFDF9sfh+LThtgxvkF80fyxxy/Ac7U9i/RcYNWrd). + +Using a `name` has various advantages: -In both cases, the router will navigate to the path `/user/erina`. +- No hardcoded URLs. +- Automatic encoding of `params`. +- Avoids URL typos. +- Bypassing path ranking, e.g. to display a lower-ranked route that matches the same path. -Full example [here](https://github.com/vuejs/vue-router/blob/dev/examples/named-routes/app.js). +Each name **must be unique** across all routes. If you add the same name to multiple routes, the router will only keep the last one. You can read more about this [in the Dynamic Routing](../advanced/dynamic-routing#Removing-routes) section. -Each name **must be unique** across all routes. If you add the same name to multiple routes, the router will only keep the last one. You can read more about this [in the Dynamic Routing](../advanced/dynamic-routing.md#Removing-routes) section. +There are various other parts of Vue Router that can be passed a location, e.g. the methods `router.push()` and `router.replace()`. We'll go into more detail about those methods in the guide to [programmatic navigation](./navigation). Just like the `to` prop, these methods also support passing a location by `name`: + +```js +router.push({ name: 'profile', params: { username: 'erina' } }) +``` diff --git a/packages/docs/guide/essentials/named-views.md b/packages/docs/guide/essentials/named-views.md index 917b73bc5..2312baa4b 100644 --- a/packages/docs/guide/essentials/named-views.md +++ b/packages/docs/guide/essentials/named-views.md @@ -8,9 +8,9 @@ Sometimes you need to display multiple views at the same time instead of nesting them, e.g. creating a layout with a `sidebar` view and a `main` view. This is where named views come in handy. Instead of having one single outlet in your view, you can have multiple and give each of them a name. A `router-view` without a name will be given `default` as its name. ```vue-html - - - + + + ``` A view is rendered by using a component, therefore multiple views require @@ -78,16 +78,19 @@ Then you can achieve the layout above with this route configuration: path: '/settings', // You could also have named views at the top component: UserSettings, - children: [{ - path: 'emails', - component: UserEmailsSubscriptions - }, { - path: 'profile', - components: { - default: UserProfile, - helper: UserProfilePreview + children: [ + { + path: 'emails', + component: UserEmailsSubscriptions + }, + { + path: 'profile', + components: { + default: UserProfile, + helper: UserProfilePreview + } } - }] + ] } ``` diff --git a/packages/docs/guide/essentials/nested-routes.md b/packages/docs/guide/essentials/nested-routes.md index 6a8ec20f4..2525411a5 100644 --- a/packages/docs/guide/essentials/nested-routes.md +++ b/packages/docs/guide/essentials/nested-routes.md @@ -8,30 +8,38 @@ Some applications' UIs are composed of components that are nested multiple levels deep. In this case, it is very common that the segments of a URL correspond to a certain structure of nested components, for example: ``` -/user/johnny/profile /user/johnny/posts -+------------------+ +-----------------+ -| User | | User | -| +--------------+ | | +-------------+ | -| | Profile | | +------------> | | Posts | | -| | | | | | | | -| +--------------+ | | +-------------+ | -+------------------+ +-----------------+ +/user/johnny/profile /user/johnny/posts +┌──────────────────┐ ┌──────────────────┐ +│ User │ │ User │ +│ ┌──────────────┐ │ │ ┌──────────────┐ │ +│ │ Profile │ │ ●────────────▶ │ │ Posts │ │ +│ │ │ │ │ │ │ │ +│ └──────────────┘ │ │ └──────────────┘ │ +└──────────────────┘ └──────────────────┘ ``` With Vue Router, you can express this relationship using nested route configurations. Given the app we created in the last chapter: -```html -
- -
+```vue + + +``` + +```vue + + ``` ```js -const User = { - template: '
User {{ $route.params.id }}
', -} +import User from './User.vue' // these are passed to `createRouter` const routes = [{ path: '/user/:id', component: User }] @@ -39,15 +47,14 @@ const routes = [{ path: '/user/:id', component: User }] The `` here is a top-level `router-view`. It renders the component matched by a top level route. Similarly, a rendered component can also contain its own, nested ``. For example, if we add one inside the `User` component's template: -```js -const User = { - template: ` -
-

User {{ $route.params.id }}

- -
- `, -} +```vue + + ``` To render components into this nested `router-view`, we need to use the `children` option in any of the routes: @@ -128,3 +135,24 @@ const routes = [ }, ] ``` + +## Omitting parent components + +We can also take advantage of the parent-child relationship between routes without needing to nest route components. This can be useful for grouping together routes with a common path prefix, or when working with more advanced features, such as [per-route navigation guards](../advanced/navigation-guards#Per-Route-Guard) or [route meta fields](../advanced/meta). + +To achieve this, we omit the `component` and `components` options from the parent route: + +```js +const routes = [ + { + path: '/admin', + children: [ + { path: '', component: AdminOverview }, + { path: 'users', component: AdminUserList }, + { path: 'users/:id', component: AdminUserDetails }, + ], + }, +] +``` + +As the parent doesn't specify a route component, the top-level `` will skip over the parent and just use the component from the relevant child instead. diff --git a/packages/docs/guide/essentials/passing-props.md b/packages/docs/guide/essentials/passing-props.md index 65bfb85bd..e5d9f6758 100644 --- a/packages/docs/guide/essentials/passing-props.md +++ b/packages/docs/guide/essentials/passing-props.md @@ -5,26 +5,74 @@ title="Learn how to pass props to route components" /> -Using `$route` in your component creates a tight coupling with the route which limits the flexibility of the component as it can only be used on certain URLs. While this is not necessarily a bad thing, we can decouple this behavior with a `props` option: +Using `$route` or `useRoute()` in your component creates a tight coupling with the route which limits the flexibility of the component as it can only be used on certain URLs. While this is not necessarily a bad thing, we can decouple this behavior with a `props` option. -We can replace +Let's return to our earlier example: + +```vue + + +``` + +with: ```js -const User = { - template: '
User {{ $route.params.id }}
' +import User from './User.vue' + +// these are passed to `createRouter` +const routes = [ + { path: '/users/:id', component: User }, +] +``` + +We can remove the direct dependency on `$route` in `User.vue` by declaring a prop instead: + +::: code-group + +```vue [Composition API] + + + + +``` + +```vue [Options API] + + + + ``` -with +::: + +We can then configure the route to pass the `id` param as a prop by setting `props: true`: ```js -const User = { - // make sure to add a prop named exactly like the route param - props: ['id'], - template: '
User {{ id }}
' -} -const routes = [{ path: '/user/:id', component: User, props: true }] +const routes = [ + { path: '/user/:id', component: User, props: true } +] ``` This allows you to use the component anywhere, which makes the component easier to reuse and test. diff --git a/packages/docs/guide/essentials/route-matching-syntax.md b/packages/docs/guide/essentials/route-matching-syntax.md index 52f8812a7..23a531793 100644 --- a/packages/docs/guide/essentials/route-matching-syntax.md +++ b/packages/docs/guide/essentials/route-matching-syntax.md @@ -24,7 +24,7 @@ const routes = [ ] ``` -But in some scenarios we don't want to add that static section `/o`/`p`. However, `orderId` is always a number while `productName` can be anything, so we can specify a custom regex for a param in parentheses: +But in some scenarios, we don't want to add that static section `/o` or `/p`. However, `orderId` is always a number while `productName` can be anything so we can specify a custom regex for a param in parentheses: ```js const routes = [ @@ -80,7 +80,7 @@ const routes = [ ] ``` -## Sensitive and strict route options +## Sensitive and strict route options By default, all routes are case-insensitive and match routes with or without a trailing slash. e.g. a route `/users` matches `/users`, `/users/`, and even `/Users/`. This behavior can be configured with the `strict` and `sensitive` options, they can be set both at a router and route level: @@ -114,6 +114,13 @@ const routes = [ Note that `*` technically also marks a parameter as optional but `?` parameters cannot be repeated. +If the route segment contains more than **just an optional parameter**, it won't match a path **without the trailing slash**. For example: + +- `/users/:uid?-:name?` won't match `/users`, only `/users/-` or even `/users/-/` +- `/users/:uid(\\d+)?:name?` won't match `/users`, only `/users/`, `/users/2`, `/users/2/`, etc + +You can play around with the matching syntax [in the playground](https://paths.esm.dev/?p=AAMsIPQg4AoKzidgQFoEXAmw-IEBBRYYOE0SkABTASiz1qgBpgQA1QTsFjAb3h2onsmlAmGIFsCXjXh4AIA.&t=/users/2/#) + ## Debugging If you need to dig how your routes are transformed into a regex to understand why a route isn't being matched or, to report a bug, you can use the [path ranker tool](https://paths.esm.dev/?p=AAMeJSyAwR4UbFDAFxAcAGAIJXMAAA..#). It supports sharing your routes through the URL. diff --git a/packages/docs/guide/index.md b/packages/docs/guide/index.md index 2d826e71e..3b31648bc 100644 --- a/packages/docs/guide/index.md +++ b/packages/docs/guide/index.md @@ -4,98 +4,202 @@ href="https://vueschool.io/courses/vue-router-4-for-everyone" title="Learn how to build powerful Single Page Applications with the Vue Router on Vue School">Watch a Free Vue Router Video Course
-Creating a Single-page Application with Vue + Vue Router feels natural: with Vue.js, we are already composing our application with components. When adding Vue Router to the mix, all we need to do is map our components to the routes and let Vue Router know where to render them. Here's a basic example: +Vue Router is the official client-side routing solution for Vue. -## HTML +Client-side routing is used by single-page applications (SPAs) to tie the browser URL to the content seen by the user. As users navigate around the application, the URL updates accordingly, but the page doesn't need to be reloaded from the server. -```html - - +Vue Router is built on Vue's component system. You configure **routes** to tell Vue Router which components to show for each URL path. -
+::: tip Prerequisites +This guide will assume that you are already familiar with Vue itself. You don't need to be a Vue expert, but you may occasionally need to refer back to [the core Vue documentation](https://vuejs.org/) for more information about certain features. +::: + +## An example + +To introduce some of the main ideas, we're going to consider this example: + +- [Vue Playground example](https://play.vuejs.org/#eNqFVVtv2zYU/itn6gArmC05btEHTXXTFcWyYZeiLfYy7UGWji02EsmRlOPA8H/fIambnaRD4Fg61++c7yN9DJqc8eirDpKANVIoA0coFOYG30kJJ9gq0cBs3+Is412AEq1B1Xmi2L+ObpvX+3IpI5+b8aFqSJ+rjANErcbQp/v3RrTchLMXlDa7CuZBl07YUoONrCl/bQPT6np9i3UtbLPv0phenVm6L3rQRgm+W79vlULeIQaZmypJ484HxyN87xzRtq3rj+SE08mViX2dlOf7vuAnh/I3xu/AiDdZEGfB+mdBz3ArGkzj0f9sRr4hy5D2zr49ykvjvmdqeTmv9RfDe4i7uM6dxsNiaF9+l0+y+Ts2Qj3cMm3oa94Zfd0py4uBzYFPO6Br3ZPaGzpme9rtQGdxg2WUgOC6Y0PDG/jbjnL0vMAsnhEsQcU4UZaMbU/z8zC3x/PYsbcN/ueilaJW03nDoy1Y+VUkT+0nvHI9PVB6PJE8M44HN2iJ27yt+9q09ek+rFR1oZg0RM5FgmvboKlEqRP/BrATX4SDH171JgBD4CIvThXJVldhP7Y7J9DtxP4nxZKk+470cnFQVuseHh2TlTduWmMEh5uiZsUdSXPAcKlOH/hIZmfEjhODRtPaozNKjyiiGcqn75Ej0Pl3lMyHp2fFeMHnEB/SRia+ict6ep/GXBWV1UGHyGtgh5O1K0KvuC8T/duieoi6tLdvYUYg+rXTmKH3jLmeKoW0owLDI7h8IrnvfAKrIargxfQ/lA0LHjmr8w3W3X3w2dVMIGWchoH9ohEl1pFRrCE2fccsgCY/1Mh3piLjaknc+pujr3TOqedk0eSSrg/BiVU3WtY5dBYMks2CkRtrzoLKGKmTOG65vNtFtON4jLh5Fb2MlnFJJ2tijVA3i40S99rdV1ngNmtr31BQXOLeCFHrRS7Zcy0eBd68jl5H13HNNjFVjxkv8eBq94unMY0mQWzZ7mJIKwtWo/pTGkaCORs2p9+Z+1+dzagWB6BFhcXdE/av+uAhf1RI0+1xMpzJFWnOuz98/gMP9Dw4icW2puhvOD+hFnVrMfqwn1peEuxJnEP7i+OM8d0X/eFgkOt+KAt0FLIj8v03Rh/hvoxeTbaozUONOiq0/aGhX6w5aY1xn7cRqkSVwEoegMCyEl4sl8sf3d1H5RhfbATdKk0C10t5cHaZlyWBHSzUJeNUFtaQww/08Tenz65xSzf+NLJaTTuP5UcARVFMACSwpL9VVyE4/QesCg/V) + +Let's start by looking at the root component, `App.vue`. + +### App.vue + +```vue + ``` -### `router-link` +This template is using two components provided by Vue Router, `RouterLink` and `RouterView`. -Note how instead of using regular `a` tags, we use a custom component `router-link` to create links. This allows Vue Router to change the URL without reloading the page, handle URL generation as well as its encoding. We will see later how to benefit from these features. +Instead of using regular `` tags, we use the custom component `RouterLink` to create links. This allows Vue Router to change the URL without reloading the page, handle URL generation, encoding, and various other features. We'll go into more detail about `RouterLink` in later sections of the guide. -### `router-view` +The `RouterView` component tells Vue Router where to render the current **route component**. That's the component that corresponds to the current URL path. It doesn't have to be in `App.vue`, you can put it anywhere to adapt it to your layout, but it does need to be included somewhere, otherwise Vue Router won't render anything. -`router-view` will display the component that corresponds to the URL. You can put it anywhere to adapt it to your layout. +The example above also uses {{ $route.fullPath }}. You can use `$route` in your component templates to access an object that represents the current route. -## JavaScript +### Creating the router instance + +The router instance is created by calling the function `createRouter()`: ```js -// 1. Define route components. -// These can be imported from other files -const Home = { template: '
Home
' } -const About = { template: '
About
' } - -// 2. Define some routes -// Each route should map to a component. -// We'll talk about nested routes later. +import { createMemoryHistory, createRouter } from 'vue-router' + +import HomeView from './HomeView.vue' +import AboutView from './AboutView.vue' + const routes = [ - { path: '/', component: Home }, - { path: '/about', component: About }, + { path: '/', component: HomeView }, + { path: '/about', component: AboutView }, ] -// 3. Create the router instance and pass the `routes` option -// You can pass in additional options here, but let's -// keep it simple for now. -const router = VueRouter.createRouter({ - // 4. Provide the history implementation to use. We are using the hash history for simplicity here. - history: VueRouter.createWebHashHistory(), - routes, // short for `routes: routes` +const router = createRouter({ + history: createMemoryHistory(), + routes, }) +``` -// 5. Create and mount the root instance. -const app = Vue.createApp({}) -// Make sure to _use_ the router instance to make the -// whole app router-aware. -app.use(router) +The `routes` option defines the routes themselves, mapping URL paths to components. The component specified by the `component` option is the one that will be rendered by the `` in our earlier `App.vue`. These route components are sometimes referred to as _views_, though they are just normal Vue components. -app.mount('#app') +Routes support various other options that we'll see later in the guide, but for now we only need `path` and `component`. + +The `history` option controls how routes are mapped onto URLs and vice versa. For the Playground example we're using `createMemoryHistory()`, which ignores the browser URL entirely and uses its own internal URL instead. That works well for the Playground, but it's unlikely to be what you'd want in a real application. Typically, you'd want to use `createWebHistory()` instead, or perhaps `createWebHashHistory()`. We'll cover that topic in more detail in the guide to [History modes](./essentials/history-mode). -// Now the app has started! +### Registering the router plugin + +Once we've created our router instance, we need to register it as a plugin by calling `use()` on our application: + +```js +createApp(App) + .use(router) + .mount('#app') ``` -By calling `app.use(router)`, we are triggering the initial navigation and giving access to `this.$router` as well as the current route as `this.$route` inside of any component: +Or, equivalently: + +```js +const app = createApp(App) +app.use(router) +app.mount('#app') +``` + +Like with most Vue plugins, the call to `use()` needs to happen before the call to `mount()`. + +If you're curious about what this plugin does, some of its responsibilities include: + +1. [Globally registering](https://vuejs.org/guide/components/registration.html#global-registration) the `RouterView` and `RouterLink` components. +2. Adding the global `$router` and `$route` properties. +3. Enabling the `useRouter()` and `useRoute()` composables. +4. Triggering the router to resolve the initial route. + +### Accessing the router and current route + +You'll likely want to access the router from elsewhere in your application. + +If you're exporting the router instance from an ES module, you could import the router instance directly where you need it. In some cases this is the best approach, but we have other options if we're inside a component. + +In component templates, the router instance is exposed as `$router`. This is similar to the `$route` property we saw earlier, but note the extra `r` on the end. + +If we're using the Options API, we can access these same two properties as `this.$router` and `this.$route` in our JavaScript code. The `HomeView.vue` component in the Playground example accesses the router that way: ```js -// Home.vue export default { - computed: { - username() { - // We will see what `params` is shortly - return this.$route.params.username - }, - }, methods: { - goToDashboard() { - if (isAuthenticated) { - this.$router.push('/dashboard') - } else { - this.$router.push('/login') - } + goToAbout() { + this.$router.push('/about') }, }, } ``` -To access the router or the route inside the `setup` function, call the `useRouter` or `useRoute` functions. We will learn more about this in [the Composition API](./advanced/composition-api.md#Accessing-the-Router-and-current-Route-inside-setup) +This method is calling `push()`, which is used for [programmatic navigation](./essentials/navigation). We'll learn more about that later. + +With the Composition API, we don't have access to the component instance via `this`, so Vue Router includes some composables that we can use instead. `AboutView.vue` in the Playground example is using that approach: + +```vue + +``` + +It's not necessary to understand all of that code right now. The key thing to notice is that the composables `useRouter()` and `useRoute()` are used to access the router instance and current route respectively. + +### Next steps + +If you'd like to see a complete example using Vite, you can use the [create-vue](https://github.com/vuejs/create-vue) scaffolding tool, which has the option to include Vue Router in its example project: + +::: code-group + +```bash [npm] +npm create vue@latest +``` + +```bash [yarn] +yarn create vue +``` + +```bash [pnpm] +pnpm create vue +``` + +::: + +The example project created by create-vue uses similar features to the ones we've seen here. You may find that a useful starting point for exploring the features introduced in the next few pages of this guide. + +## Conventions in this guide + +### Single-File Components + +Vue Router is most commonly used in applications built using a bundler (e.g. Vite) and [SFCs](https://vuejs.org/guide/introduction.html#single-file-components) (i.e. `.vue` files). Most of the examples in this guide will be written in that style, but Vue Router itself doesn't require you to use build tools or SFCs. + +For example, if you're using the _global builds_ of [Vue](https://vuejs.org/guide/quick-start.html#using-vue-from-cdn) and [Vue Router](../installation#Direct-Download-CDN), the libraries are exposed via global objects, rather than imports: + +```js +const { createApp } = Vue +const { createRouter, createWebHistory } = VueRouter +``` + +### Component API style + +Vue Router can be used with both the Composition API and the Options API. Where relevant, the examples in this guide will show components written in both styles. Composition API examples will typically use ` ``` -`route` 对象是一个响应式对象,所以它的任何属性都可以被监听,但你应该**避免监听整个 `route`** 对象。在大多数情况下,你应该直接监听你期望改变的参数。 +`route` 对象是一个响应式对象。在多数情况下,你应该**避免监听整个 `route`** 对象,同时直接监听你期望改变的参数。 -```js +```vue + ``` -请注意,在模板中我们仍然可以访问 `$router` 和 `$route`,所以不需要在 `setup` 中返回 `router` 或 `route`。 +请注意,在模板中我们仍然可以访问 `$router` 和 `$route`,所以如果你只在模板中使用这些对象的话,是不需要 `useRouter` 或 `useRoute` 的。 ## 导航守卫 -虽然你仍然可以通过 `setup` 函数来使用组件内的导航守卫,但 Vue Router 将更新和离开守卫作为 组合式 API 函数公开: +Vue Router 将更新和离开守卫作为组合式 API 函数公开: -```js +```vue + ``` 组合式 API 守卫也可以用在任何由 `` 渲染的组件中,它们不必像组件内守卫那样直接用在路由组件上。 @@ -94,40 +88,34 @@ export default { Vue Router 将 RouterLink 的内部行为作为一个组合式函数 (composable) 公开。它接收一个类似 `RouterLink` 所有 prop 的响应式对象,并暴露底层属性来构建你自己的 `RouterLink` 组件或生成自定义链接: -```js +```vue + ``` 注意在 RouterLink 的 `v-slot` 中可以访问与 `useLink` 组合式函数相同的属性。 diff --git a/packages/docs/zh/guide/advanced/data-fetching.md b/packages/docs/zh/guide/advanced/data-fetching.md index e060fcfb7..4355a30d3 100644 --- a/packages/docs/zh/guide/advanced/data-fetching.md +++ b/packages/docs/zh/guide/advanced/data-fetching.md @@ -10,11 +10,13 @@ ## 导航完成后获取数据 -当你使用这种方式时,我们会马上导航和渲染组件,然后在组件的 created 钩子中获取数据。这让我们有机会在数据获取期间展示一个 loading 状态,还可以在不同视图间展示不同的 loading 状态。 +当你使用这种方式时,我们会马上导航和渲染组件,然后在组件中获取数据。这让我们有机会在数据获取期间展示一个 loading 状态,还可以在不同视图间展示不同的 loading 状态。 -假设我们有一个 `Post` 组件,需要基于 `$route.params.id` 获取文章数据: +假设我们有一个 `Post` 组件,需要基于 `route.params.id` 获取文章数据: -```html +::: code-group + +```vue [Composition API] + + ``` -```js +```vue [Options API] + + + ``` +::: + ## 在导航完成前获取数据 通过这种方式,我们在导航转入新的路由前获取数据。我们可以在接下来的组件的 `beforeRouteEnter` 守卫中获取数据,当数据获取成功后只调用 `next` 方法: @@ -81,20 +129,29 @@ export default { } }, beforeRouteEnter(to, from, next) { - getPost(to.params.id, (err, post) => { - next(vm => vm.setData(err, post)) - }) + try { + const post = await getPost(to.params.id) + // `setPost` 方法定义在下面的代码中 + next(vm => vm.setPost(post)) + } catch (err) { + // `setError` 方法定义在下面的代码中 + next(vm => vm.setError(err)) + } }, // 路由改变前,组件就已经渲染完了 // 逻辑稍稍不同 async beforeRouteUpdate(to, from) { this.post = null - try { - this.post = await getPost(to.params.id) - } catch (error) { - this.error = error.toString() - } + getPost(to.params.id).then(this.setPost).catch(this.setError) }, + methods: { + setPost(post) { + this.post = post + }, + setError(err) { + this.error = err.toString() + } + } } ``` diff --git a/packages/docs/zh/guide/advanced/dynamic-routing.md b/packages/docs/zh/guide/advanced/dynamic-routing.md index 5ad3bcace..ba7b602d3 100644 --- a/packages/docs/zh/guide/advanced/dynamic-routing.md +++ b/packages/docs/zh/guide/advanced/dynamic-routing.md @@ -5,7 +5,7 @@ title="Learn how to add routes at runtime" /> -对路由的添加通常是通过 [`routes` 选项](../../api/#routes)来完成的,但是在某些情况下,你可能想在应用程序已经运行的时候添加或删除路由。具有可扩展接口(如 [Vue CLI UI](https://cli.vuejs.org/dev-guide/ui-api.html) )这样的应用程序可以使用它来扩展应用程序。 +对路由的添加通常是通过 `routes` 选项来完成的,但是在某些情况下,你可能想在应用程序已经运行的时候添加或删除路由。具有可扩展接口(如 [Vue CLI UI](https://cli.vuejs.org/dev-guide/ui-api.html) )这样的应用程序可以使用它来扩展应用程序。 ## 添加路由 @@ -30,7 +30,7 @@ router.addRoute({ path: '/about', component: About }) ```js router.addRoute({ path: '/about', component: About }) -// 我们也可以使用 this.$route 或 route = useRoute() (在 setup 中) +// 我们也可以使用 this.$route 或 useRoute() router.replace(router.currentRoute.value.fullPath) ``` diff --git a/packages/docs/zh/guide/advanced/extending-router-link.md b/packages/docs/zh/guide/advanced/extending-router-link.md index 572302447..16a21996c 100644 --- a/packages/docs/zh/guide/advanced/extending-router-link.md +++ b/packages/docs/zh/guide/advanced/extending-router-link.md @@ -9,7 +9,28 @@ RouterLink 组件提供了足够的 `props` 来满足大多数基本应用程序 让我们扩展 RouterLink 来处理外部链接,并在 `AppLink.vue` 文件中添加一个自定义的 `inactive-class`: -```vue +::: code-group + +```vue [Composition API] + + +``` +```vue [Options API] + + ``` +::: + 如果你喜欢使用渲染函数或创建 `computed` 属性,你可以使用 [Composition API](./composition-api.md) 中的 `useLink` : ```js diff --git a/packages/docs/zh/guide/advanced/lazy-loading.md b/packages/docs/zh/guide/advanced/lazy-loading.md index c4e0dffdf..80e2829d2 100644 --- a/packages/docs/zh/guide/advanced/lazy-loading.md +++ b/packages/docs/zh/guide/advanced/lazy-loading.md @@ -17,7 +17,11 @@ const UserDetails = () => import('./views/UserDetails.vue') const router = createRouter({ // ... - routes: [{ path: '/users/:id', component: UserDetails }], + routes: [ + { path: '/users/:id', component: UserDetails } + // 或在路由定义里直接使用它 + { path: '/users/:id', component: () => import('./views/UserDetails.vue') }, + ], }) ``` diff --git a/packages/docs/zh/guide/advanced/meta.md b/packages/docs/zh/guide/advanced/meta.md index 4e1ed64aa..1063e01f9 100644 --- a/packages/docs/zh/guide/advanced/meta.md +++ b/packages/docs/zh/guide/advanced/meta.md @@ -17,13 +17,13 @@ const routes = [ path: 'new', component: PostsNew, // 只有经过身份验证的用户才能创建帖子 - meta: { requiresAuth: true } + meta: { requiresAuth: true }, }, { path: ':id', component: PostsDetail // 任何人都可以阅读文章 - meta: { requiresAuth: false } + meta: { requiresAuth: false }, } ] } @@ -38,7 +38,7 @@ const routes = [ 例如,根据上面的路由配置,`/posts/new` 这个 URL 将会匹配父路由记录 (`path: '/posts'`) 以及子路由记录 (`path: 'new'`)。 -一个路由匹配到的所有路由记录会暴露为 `$route` 对象(还有在导航守卫中的路由对象)的`$route.matched` 数组。我们需要遍历这个数组来检查路由记录中的 `meta` 字段,但是 Vue Router 还为你提供了一个 `$route.meta` 方法,它是一个非递归合并**所有 `meta`** 字段的(从父字段到子字段)的方法。这意味着你可以简单地写 +一个路由匹配到的所有路由记录会暴露为 `route` 对象(还有在导航守卫中的路由对象)的`route.matched` 数组。我们需要遍历这个数组来检查路由记录中的 `meta` 字段,但是 Vue Router 还为你提供了一个 `route.meta` 方法,它是一个非递归合并**所有 `meta`** 字段(从父字段到子字段)的方法。这意味着你可以简单地写 ```js router.beforeEach((to, from) => { @@ -58,12 +58,17 @@ router.beforeEach((to, from) => { ## TypeScript -可以通过扩展 `RouteMeta` 接口来输入 meta 字段: +也可以继承来自 `vue-router` 中的 `RouteMeta` 来为 meta 字段添加类型: ```ts -// typings.d.ts or router.ts +// 这段可以直接添加到你的任何 `.ts` 文件中,例如 `router.ts` +// 也可以添加到一个 `.d.ts` 文件中。确保这个文件包含在 +// 项目的 `tsconfig.json` 中的 "file" 字段内。 import 'vue-router' +// 为了确保这个文件被当作一个模块,添加至少一个 `export` 声明 +export {} + declare module 'vue-router' { interface RouteMeta { // 是可选的 diff --git a/packages/docs/zh/guide/advanced/navigation-failures.md b/packages/docs/zh/guide/advanced/navigation-failures.md index 625780750..79460435d 100644 --- a/packages/docs/zh/guide/advanced/navigation-failures.md +++ b/packages/docs/zh/guide/advanced/navigation-failures.md @@ -62,12 +62,24 @@ if (isNavigationFailure(failure, NavigationFailureType.aborted)) { 如果你忽略第二个参数: `isNavigationFailure(failure)`,那么就只会检查这个 `failure` 是不是一个 _Navigation Failure_。 ::: +## 全局导航故障 + +你可以用 [`router.afterEach()` 导航守卫](./navigation-guards.md#Global-After-Hooks)检测全局导航故障: + +```ts +router.afterEach((to, from, failure) => { + if (failure) { + sendToAnalytics(to, from, failure) + } +}) +``` + ## 鉴别导航故障 正如我们在一开始所说的,有不同的情况会导致导航的中止,所有这些情况都会导致不同的 _Navigation Failure_。它们可以用 `isNavigationFailure` 和 `NavigationFailureType` 来区分。总共有三种不同的类型: - `aborted`:在导航守卫中返回 `false` 中断了本次导航。 -- `cancelled`: 在当前导航还没有完成之前又有了一个新的导航。比如,在等待导航守卫的过程中又调用了 `router.push`。 +- `cancelled`: 在当前导航完成之前又有了一个新的导航。比如,在等待导航守卫的过程中又调用了 `router.push`。 - `duplicated`:导航被阻止,因为我们已经在目标位置了。 ## *导航故障*的属性 diff --git a/packages/docs/zh/guide/advanced/navigation-guards.md b/packages/docs/zh/guide/advanced/navigation-guards.md index 7767b38ca..e84e6037b 100644 --- a/packages/docs/zh/guide/advanced/navigation-guards.md +++ b/packages/docs/zh/guide/advanced/navigation-guards.md @@ -31,7 +31,7 @@ router.beforeEach((to, from) => { 可以返回的值如下: - `false`: 取消当前的导航。如果浏览器的 URL 改变了(可能是用户手动或者浏览器后退按钮),那么 URL 地址会重置到 `from` 路由对应的地址。 -- 一个[路由地址](../../api/#routelocationraw): 通过一个路由地址跳转到一个不同的地址,就像你调用 [`router.push()`](../../api/#push) 一样,你可以设置诸如 `replace: true` 或 `name: 'home'` 之类的配置。当前的导航被中断,然后进行一个新的导航,就和 `from` 一样。 +- 一个[路由地址](../../api/#routelocationraw): 通过一个路由地址重定向到一个不同的地址,如同调用 `router.push()`,且可以传入诸如 `replace: true` 或 `name: 'home'` 之类的选项。它会中断当前的导航,同时用相同的 `from` 创建一个新导航。 ```js router.beforeEach(async (to, from) => { @@ -47,7 +47,7 @@ router.beforeEach((to, from) => { }) ``` -如果遇到了意料之外的情况,可能会抛出一个 `Error`。这会取消导航并且调用 [`router.onError()`](../../api/#onerror) 注册过的回调。 +如果遇到了意料之外的情况,可能会抛出一个 `Error`。这会取消导航并且调用 [`router.onError()`](../../api/interfaces/Router.md#onError) 注册过的回调。 如果什么都没有,`undefined` 或返回 `true`,**则导航是有效的**,并调用下一个导航守卫 @@ -63,7 +63,7 @@ router.beforeEach(async (to, from) => { ### 可选的第三个参数 `next` -在之前的 Vue Router 版本中,也是可以使用 _第三个参数_ `next` 的。这是一个常见的错误来源,可以通过 [RFC](https://github.com/vuejs/rfcs/blob/master/active-rfcs/0037-router-return-guards.md#motivation) 来消除错误。然而,它仍然是被支持的,这意味着你可以向任何导航守卫传递第三个参数。在这种情况下,**确保 `next`** 在任何给定的导航守卫中都被**严格调用一次**。它可以出现多于一次,但是只能在所有的逻辑路径都不重叠的情况下,否则钩子永远都不会被解析或报错。这里有一个在用户未能验证身份时重定向到`/login`的**错误用例**: +在之前的 Vue Router 版本中,还可以使用 _第三个参数_ `next` 。这是一个常见的错误来源,我们经过 [RFC](https://github.com/vuejs/rfcs/blob/master/active-rfcs/0037-router-return-guards.md#motivation) 讨论将其移除。然而,它仍然是被支持的,这意味着你可以向任何导航守卫传递第三个参数。在这种情况下,**确保 `next`** 在任何给定的导航守卫中都被**严格调用一次**。它可以出现多于一次,但是只能在所有的逻辑路径都不重叠的情况下,否则钩子永远都不会被解析或报错。这里有一个在用户未能验证身份时重定向到`/login`的**错误用例**: ```js // BAD @@ -86,7 +86,7 @@ router.beforeEach((to, from, next) => { ## 全局解析守卫 -你可以用 `router.beforeResolve` 注册一个全局守卫。这和 `router.beforeEach` 类似,因为它在**每次导航**时都会触发,不同的是,解析守卫刚好会在导航被确认之前、**所有组件内守卫和异步路由组件被解析之后**调用。这里有一个例子,确保用户可以访问[自定义 meta](./meta.md) 属性 `requiresCamera` 的路由: +你可以用 `router.beforeResolve` 注册一个全局守卫。这和 `router.beforeEach` 类似,因为它在**每次导航**时都会触发,不同的是,解析守卫刚好会在导航被确认之前、**所有组件内守卫和异步路由组件被解析之后**调用。这里有一个例子,根据路由在[元信息](./meta.md)中的 `requiresCamera` 属性确保用户访问摄像头的权限: ```js router.beforeResolve(async to => { @@ -134,6 +134,25 @@ router.afterEach((to, from, failure) => { 了解更多关于 navigation failures 的信息在[它的指南](./navigation-failures.md)中。 + +## 在守卫内的全局注入 + +从 Vue 3.3 开始,你可以在导航守卫内使用 `inject()` 方法。这在注入像 [pinia stores](https://pinia.vuejs.org) 这样的全局属性时很有用。在 `app.provide()` 中提供的所有内容都可以在 `router.beforeEach()`、`router.beforeResolve()`、`router.afterEach()` 内获取到: + +```ts +// main.ts +const app = createApp(App) +app.provide('global', 'hello injections') + +// router.ts or main.ts +router.beforeEach((to, from) => { + const global = inject('global') // 'hello injections' + // a pinia store + const userStore = useAuthStore() + // ... +}) +``` + ## 路由独享的守卫 你可以直接在路由配置上定义 `beforeEnter` 守卫: @@ -179,7 +198,28 @@ const routes = [ ] ``` -请注意,你也可以通过使用[路径 meta 字段](./meta.md)和[全局导航守卫](#global-before-guards)来实现类似的行为。 +当配合[嵌套路由](../essentials/nested-routes)使用时,父路由和子路由都可以使用 `beforeEnter`。如果放在父级路由上,路由在具有相同父级的子路由之间移动时,它不会被触发。例如: + +```js +const routes = [ + { + path: '/user', + beforeEnter() { + // ... + }, + children: [ + { path: 'list', component: UserList }, + { path: 'details', component: UserDetails }, + ], + }, +] +``` + +示例中的 `beforeEnter` 在 `/user/list` 和 `/user/details` 之间移动时不会被调用,因为它们共享相同的父级路由。如果我们直接将 `beforeEnter` 守卫放在 `details` 路由上,那么在这两个路由之间移动时就会被调用。 + +::: tip +你也可以通过使用[路由元信息字段](./meta.md)和全局导航守卫来实现类似的行为。 +::: ## 组件内的守卫 @@ -193,9 +233,9 @@ const routes = [ - `beforeRouteUpdate` - `beforeRouteLeave` -```js -const UserDetails = { - template: `...`, +```vue + ``` `beforeRouteEnter` 守卫 **不能** 访问 `this`,因为守卫在导航确认前被调用,因此即将登场的新组件还没被创建。 @@ -246,7 +287,7 @@ beforeRouteLeave (to, from) { ### 使用组合 API -如果你正在使用[组合 API 和 `setup` 函数](https://cn.vuejs.org/api/composition-api-setup.html)来编写组件,你可以通过 `onBeforeRouteUpdate` 和 `onBeforeRouteLeave` 分别添加 update 和 leave 守卫。 请参考[组合 API 部分](./composition-api.md#导航守卫)以获得更多细节。 +如果你正在使用组合式 API 编写组件,你可以通过 `onBeforeRouteUpdate` 和 `onBeforeRouteLeave` 分别添加 update 和 leave 守卫。 请参考[组合式 API 部分](./composition-api.md#导航守卫)以获得更多细节。 ## 完整的导航解析流程 diff --git a/packages/docs/zh/guide/advanced/router-view-slot.md b/packages/docs/zh/guide/advanced/router-view-slot.md new file mode 100644 index 000000000..eec3a4461 --- /dev/null +++ b/packages/docs/zh/guide/advanced/router-view-slot.md @@ -0,0 +1,73 @@ +# RouterView 插槽 + +RotuerView 组件暴露了一个插槽,可以用来渲染路由组件: + +```vue-html + + + +``` + +上面的代码等价于不带插槽的 ``,但是当我们想要获得其他功能时,插槽提供了额外的扩展性。 + +## KeepAlive & Transition + +当在处理 [KeepAlive](https://vuejs.org/guide/built-ins/keep-alive.html) 组件时,我们通常想要保持路由组件活跃,而不是 RouterView 本身。为了实现这个目的,我们可以将 KeepAlive 组件放置在插槽内: + +```vue-html + + + + + +``` + +类似地,插槽允许我们使用一个 [Transition](https://vuejs.org/guide/built-ins/transition.html) 组件来实现在路由组件之间切换时实现过渡效果: + +```vue-html + + + + + +``` + +我们也可以在 Transition 组件内使用 KeepAlive 组件: + +```vue-html + + + + + + + +``` + +关于更多 RouterView 组件和 Transition 组件之间的互动,请参考 [Transitions](./transitions) 指南。 + +## 传递 props 和插槽 + +我们可以利用其插槽给路由组件传递 props 或插槽: + +```vue-html + + +

Some slotted content

+
+
+``` + +实践中通常不会这么做,因为这样会导致所有路由组件**都使用相同的 props 和插槽**。请查阅[传递 props 给路由组件](../essentials/passing-props)获取其他传递 props 的方式。 + +## 模板引用 + +使用插槽可以让我们直接将[模板引用](https://vuejs.org/guide/essentials/template-refs.html)放置在路由组件上: + +```vue-html + + + +``` + +而如果我们将引用放在 `` 上,那引用将会被 RouterView 的实例填充,而不是路由组件本身。 diff --git a/packages/docs/zh/guide/advanced/scroll-behavior.md b/packages/docs/zh/guide/advanced/scroll-behavior.md index c34d043db..f0d77b19a 100644 --- a/packages/docs/zh/guide/advanced/scroll-behavior.md +++ b/packages/docs/zh/guide/advanced/scroll-behavior.md @@ -43,7 +43,8 @@ const router = createRouter({ // 也可以这么写 // el: document.getElementById('main'), el: '#main', - top: -10, + // 在元素上 10 像素 + top: 10, } }, }) diff --git a/packages/docs/zh/guide/advanced/transitions.md b/packages/docs/zh/guide/advanced/transitions.md index cc10eebcc..aaabd9e39 100644 --- a/packages/docs/zh/guide/advanced/transitions.md +++ b/packages/docs/zh/guide/advanced/transitions.md @@ -5,9 +5,9 @@ title="Learn about route transitions" /> -想要在你的路径组件上使用转场,并对导航进行动画处理,你需要使用 [v-slot API](/guide/advanced/composition-api#uselink): +想要在你的路径组件上使用转场,并对导航进行动画处理,你需要使用 [`` 插槽](./router-view-slot): -```vue-html +```html @@ -36,7 +36,7 @@ const routes = [ ] ``` -```vue-html +```html @@ -49,7 +49,7 @@ const routes = [ 也可以根据目标路由和当前路由之间的关系,动态地确定使用的过渡。使用和刚才非常相似的片段: -```vue-html +```html diff --git a/packages/docs/zh/guide/essentials/active-links.md b/packages/docs/zh/guide/essentials/active-links.md new file mode 100644 index 000000000..76f93a437 --- /dev/null +++ b/packages/docs/zh/guide/essentials/active-links.md @@ -0,0 +1,80 @@ + + +# Active links + +It's common for applications to have a navigation component that renders a list of RouterLink components. Within that list, we might want to style links to the currently active route differently from the others. + +The RouterLink component adds two CSS classes to active links, `router-link-active` and `router-link-exact-active`. To understand the difference between them, we first need to consider how Vue Router decides that a link is _active_. + +## When are links active? + +A RouterLink is considered to be ***active*** if: + +1. It matches the same route record (i.e. configured route) as the current location. +2. It has the same values for the `params` as the current location. + +If you're using [nested routes](./nested-routes), any links to ancestor routes will also be considered active if the relevant `params` match. + +Other route properties, such as the [`query`](../../api/interfaces/RouteLocationNormalized#query), are not taken into account. + +The path doesn't necessarily need to be a perfect match. For example, using an [`alias`](./redirect-and-alias#Alias) would still be considered a match, so long as it resolves to the same route record and `params`. + +If a route has a [`redirect`](./redirect-and-alias#Redirect), it won't be followed when checking whether a link is active. + +## Exact active links + +An ***exact*** match does not include ancestor routes. + +Let's imagine we have the following routes: + +```js +const routes = [ + { + path: '/user/:username', + component: User, + children: [ + { + path: 'role/:roleId', + component: Role, + } + ] + } +] +``` + +Then consider these two links: + +```vue-html + + User + + + Role + +``` + +If the current location path is `/user/erina/role/admin` then these would both be considered _active_, so the class `router-link-active` would be applied to both links. But only the second link would be considered _exact_, so only that second link would have the class `router-link-exact-active`. + +## Configuring the classes + +The RouterLink component has two props, `activeClass` and `exactActiveClass`, that can be used to change the names of the classes that are applied: + +```vue-html + +``` + +The default class names can also be changed globally by passing the `linkActiveClass` and `linkExactActiveClass` options to `createRouter()`: + +```js +const router = createRouter({ + linkActiveClass: 'border-indigo-500', + linkExactActiveClass: 'border-indigo-700', + // ... +}) +``` + +See [Extending RouterLink](../advanced/extending-router-link) for more advanced customization techniques using the `v-slot` API. diff --git a/packages/docs/zh/guide/essentials/dynamic-matching.md b/packages/docs/zh/guide/essentials/dynamic-matching.md index 7d0646f1e..5ba892e86 100644 --- a/packages/docs/zh/guide/essentials/dynamic-matching.md +++ b/packages/docs/zh/guide/essentials/dynamic-matching.md @@ -8,9 +8,7 @@ 很多时候,我们需要将给定匹配模式的路由映射到同一个组件。例如,我们可能有一个 `User` 组件,它应该对所有用户进行渲染,但用户 ID 不同。在 Vue Router 中,我们可以在路径中使用一个动态字段来实现,我们称之为 _路径参数_ : ```js -const User = { - template: '
User
', -} +import User from './User.vue' // 这些都会传递给 `createRouter` const routes = [ @@ -21,22 +19,25 @@ const routes = [ 现在像 `/users/johnny` 和 `/users/jolyne` 这样的 URL 都会映射到同一个路由。 -_路径参数_ 用冒号 `:` 表示。当一个路由被匹配时,它的 _params_ 的值将在每个组件中以 `this.$route.params` 的形式暴露出来。因此,我们可以通过更新 `User` 的模板来呈现当前的用户 ID: +_路径参数_ 用冒号 `:` 表示。当一个路由被匹配时,它的 _params_ 的值将在每个组件中以 `route.params` 的形式暴露出来。因此,我们可以通过更新 `User` 的模板来呈现当前的用户 ID: -```js -const User = { - template: '
User {{ $route.params.id }}
', -} +```vue + ``` 你可以在同一个路由中设置有多个 _路径参数_,它们会映射到 `$route.params` 上的相应字段。例如: -| 匹配模式 | 匹配路径 | \$route.params | +| 匹配模式 | 匹配路径 | route.params | | ------------------------------ | ------------------------ | ---------------------------------------- | | /users/:username | /users/eduardo | `{ username: 'eduardo' }` | | /users/:username/posts/:postId | /users/eduardo/posts/123 | `{ username: 'eduardo', postId: '123' }` | -除了 `$route.params` 之外,`$route` 对象还公开了其他有用的信息,如 `$route.query`(如果 URL 中存在参数)、`$route.hash` 等。你可以在 [API 参考](../../api/#routelocationnormalized)中查看完整的细节。 +除了 `route.params` 之外,`route` 对象还公开了其他有用的信息,如 `route.query`(如果 URL 中存在参数)、`route.hash` 等。你可以在 [API 参考](../../api/#routelocationnormalized)中查看完整的细节。 这个例子的 demo 可以在[这里](https://codesandbox.io/s/route-params-vue-router-examples-mlb14?from-embed&initialpath=%2Fusers%2Feduardo%2Fposts%2F1)找到。 @@ -59,32 +60,68 @@ const User = { 要对同一个组件中参数的变化做出响应的话,你可以简单地 watch `$route` 对象上的任意属性,在这个场景中,就是 `$route.params` : -```js -const User = { - template: '...', +::: code-group + +```vue [Composition API] + +``` + +```vue [Options API] + ``` -或者,使用 `beforeRouteUpdate` [导航守卫](../advanced/navigation-guards.md),它也可以取消导航: +::: -```js -const User = { - template: '...', +或者,使用 `beforeRouteUpdate` [导航守卫](../advanced/navigation-guards.md),它还允许你取消导航: + +::: code-group + +```vue [Composition API] + +``` + +```vue [Options API] + ``` +::: + ## 捕获所有路由或 404 Not found 路由 ``` -也可以使用 [`FallbackResource`](https://httpd.apache.org/docs/2.2/mod/mod_dir.html#fallbackresource) 代替 `mod_rewrite`。 +也可以使用 [`FallbackResource`](https://httpd.apache.org/docs/2.4/mod/mod_dir.html#fallbackresource) 代替 `mod_rewrite`。 ### nginx @@ -186,7 +202,7 @@ rewrite { } ``` -## Caveat +## 附加说明 这有一个注意事项。你的服务器将不再报告 404 错误,因为现在所有未找到的路径都会显示你的 `index.html` 文件。为了解决这个问题,你应该在你的 Vue 应用程序中实现一个万能的路由来显示 404 页面。 diff --git a/packages/docs/zh/guide/essentials/named-routes.md b/packages/docs/zh/guide/essentials/named-routes.md index 4541f3700..da660ff85 100644 --- a/packages/docs/zh/guide/essentials/named-routes.md +++ b/packages/docs/zh/guide/essentials/named-routes.md @@ -5,37 +5,41 @@ title="Learn about the named routes" /> -除了 `path` 之外,你还可以为任何路由提供 `name`。这有以下优点: - -- 没有硬编码的 URL -- `params` 的自动编码/解码。 -- 防止你在 url 中出现打字错误。 -- 绕过路径排序(如显示一个) +当创建一个路由时,我们可以选择给路由一个 `name`: ```js const routes = [ { path: '/user/:username', - name: 'user', - component: User, - }, + name: 'profile', // [!code highlight] + component: User + } ] ``` -要链接到一个命名的路由,可以向 `router-link` 组件的 `to` 属性传递一个对象: +然后我们可以使用 `name` 而不是 `path` 来传递 `to` 属性给 ``: ```vue-html - - User + + User profile ``` -这跟代码调用 `router.push()` 是一回事: +上述示例将创建一个指向 `/user/erina` 的链接。 + +- [在演练场上查看](https://play.vuejs.org/#eNqtVVtP2zAU/itWNqlFauNNIB6iUMEQEps0NjH2tOzBtKY1JLZlO6VTlP++4+PcelnFwyRofe7fubaKCiZk/GyjJBKFVsaRiswNZ45faU1q8mRUQUbrko8yuaPwlRfK/LkV1sHXpGHeq9JxMzScGmT19t5xkMaUaR1vOb9VBe+kntgWXz2Cs06O1LbCTwvRW7knGnEm50paRwIYcrEFd1xlkpBVyCQ5lN74ZOJV0Nom5JcnCFRCM7dKyIiOJkSygsNzBZiBmivAI7l0SUipRvuhCfPge7uWHBiGZPctS0iLJv7T2/YutFFPIt+JjgUJPn7DZ32CtWg7PIZ/4BASg7txKE6gC1VKNx69gw6NTqJJ1HQK5iR1vNA52M+8Yrr6OLuD+AuCtbQpBQYK9Oy6NAZAhLI1KKuKvEc69jSp65Tqw/oh3V7f00P9MsdveOWiecE75DDNhXwhiVMXWVRttYbUWdRpE2xOZ0sHxq1v2jl/a5jQyZ042Mv/HKjvt2aGFTCXFWmnAsTcCMkAxw4SHIjG9E2AUtpUusWyFvyVUGCltBsFmJB2W/dHZCHWswdYLwJ/XiulnrNr323zcQeodthDuAHTgmm4aEqCH1zsrBHYLIISheyyqD9Nnp1FK+e0TSgtpX5ZxrBBtNe4PItP4w8Q07oBN+a2mD4a9erPzDN4bzY1iy5BiS742imV2ynT4l8h9hQvz+Pz+COU/pGCdyrkgm/Qt3ddw/5Cms7CLXsSy50k/dJDT8037QTcuq1kWZ6r1y/Ic6bkHdD5is9fDvCf7SZA/m44ZLfmg+QcM0vugvjmxx3fwLsTFmpRwlwdE95zq/LSYwxqn0q5ANgDPUT7GXsm5PLB3mwcl7ZNygPFaqA+NvL6SOo93NP4bFDF9sfh+LThtgxvkF80fyxxy/Ac7U9i/RcYNWrd)。 + +使用 `name` 有很多优点: + +- 没有硬编码的 URL。 +- `params` 的自动编码/解码。 +- 防止你在 URL 中出现打字错误。 +- 绕过路径排序,例如展示一个匹配相同路径但排序较低的路由。 + +所有路由的命名**都必须是唯一的**。如果为多条路由添加相同的命名,路由器只会保留最后那一条。你可以在[动态路由](../advanced/dynamic-routing.md#Removing-routes)章节了解更多。 + +Vue Router 有很多其他部分可以传入网址,例如 `router.push()` 和 `router.replace()` 方法。我们将在[编程式导航](./navigation.md)指南中详细介绍这些方法。就像 `to` 属性一样,这些方法也支持通过 `name` 传入网址: ```js router.push({ name: 'user', params: { username: 'erina' } }) ``` - -在这两种情况下,路由将导航到路径 `/user/erina`。 - -完整的例子在[这里](https://github.com/vuejs/vue-router/blob/dev/examples/named-routes/app.js). diff --git a/packages/docs/zh/guide/essentials/named-views.md b/packages/docs/zh/guide/essentials/named-views.md index e87f9eb25..b9c568a9d 100644 --- a/packages/docs/zh/guide/essentials/named-views.md +++ b/packages/docs/zh/guide/essentials/named-views.md @@ -8,9 +8,9 @@ 有时候想同时 (同级) 展示多个视图,而不是嵌套展示,例如创建一个布局,有 `sidebar` (侧导航) 和 `main` (主内容) 两个视图,这个时候命名视图就派上用场了。你可以在界面中拥有多个单独命名的视图,而不是只有一个单独的出口。如果 `router-view` 没有设置名字,那么默认为 `default`。 ```vue-html - - - + + + ``` 一个视图使用一个组件渲染,因此对于同个路由,多个视图就需要多个组件。确保正确使用 `components` 配置 (带上 **s**): @@ -59,7 +59,7 @@ const router = createRouter({ `UserSettings` 组件的 `