Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(vue): allow to change global/inject route name #797

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading