Skip to content

Commit

Permalink
feat(vue): allow to change global/inject route name
Browse files Browse the repository at this point in the history
Closes #796
  • Loading branch information
iamandrewluca committed Dec 12, 2024
1 parent ca40646 commit 071c2d2
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 4 deletions.
24 changes: 24 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -388,6 +388,17 @@ const route = inject('route');
</script>
```

With `<script setup lang="ts">` you can use TypeScript to type the `route` function:

```vue
<script setup>
import { inject } from 'vue';
import { route as routeFn } from 'ziggy-js'
const route = inject<typeof routeFn>('route')
</script>
```

If you are not using the `@routes` Blade directive, import Ziggy's configuration too and pass it to `.use()`:

```js
Expand All @@ -409,6 +420,19 @@ declare module 'vue' {
}
```

If you want to change the name of the `route` global or inject, you can pass a custom name to the `ZiggyVue` plugin:

```js
createApp(App).use(ZiggyVue, {
globalRouteFnName: '$route', // Default is `"route"`
injectRouteFnName: '$route', // Default is `"route"`
});
```

> [!NOTE]
> If changing the `globalRouteFnName`, make sure to update `ComponentCustomProperties` in your `.d.ts` file accordingly.
> If changing the `injectRouteFnName`, make sure to update the `inject` call in your Vue components accordingly.
### React

Ziggy includes a `useRoute()` hook to make it easy to use the `route()` helper in your React app:
Expand Down
2 changes: 2 additions & 0 deletions src/js/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,8 @@ interface Config {
pathname?: string;
search?: string;
};
globalRouteFnName?: string;
injectRouteFnName?: string;
}

/**
Expand Down
14 changes: 10 additions & 4 deletions src/js/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,17 +7,23 @@ export function route(name, params, absolute, config) {
}

export const ZiggyVue = {
install(app, options) {
install(app, pluginOptions = {}) {
const {
globalRouteFnName = 'route',
injectRouteFnName = 'route',
...options
} = pluginOptions;

const r = (name, params, absolute, config = options) =>
route(name, params, absolute, config);

if (parseInt(app.version) > 2) {
app.config.globalProperties.route = r;
app.provide('route', r);
app.config.globalProperties[globalRouteFnName] = r;
app.provide(injectRouteFnName, r);
} else {
app.mixin({
methods: {
route: r,
[globalRouteFnName]: r,
},
});
}
Expand Down

0 comments on commit 071c2d2

Please sign in to comment.