tighten / ziggy

Use your Laravel routes in JavaScript.
MIT License
3.91k stars 247 forks source link

How to use route() in setup() of vue 3 component? #454

Closed sprklinginfo closed 3 years ago

sprklinginfo commented 3 years ago

Ziggy version

v1.3.5

Laravel version

v8.54.0

Description

Working on a project with Laravel/Inertia stack (from breeze starter kit). Here is a part of code in app.js

createInertiaApp({
    title: (title) => `${title} - ${appName}`,
    resolve: (name) => require(`./Pages/${name}.vue`),
    setup({ el, app, props, plugin }) {
        return createApp({ render: () => h(app, props) })
            .use(plugin)
            .use(ElementPlus, { locale })
            .mixin({ methods: route }) // avoid namespace conflict with Element Plus NaveMenu component
            .mount(el);
    },
});

I am trying to use composition API on my components. I got 'route() undefined' error if I try using 'ctx.route()'. So my question is how I can use route() helper in setup() to access route params? Thanks!

Ziggy call and context

//

Ziggy configuration

//

Route definition

//
sprklinginfo commented 3 years ago

can anyone help pls? or point me in the right direction? Thanks!!

bakerkretzmar commented 3 years ago

@sprklinginfo I haven't used the composition API but I think you don't have access to any methods inside setup() because there's no component instance yet: https://v3.vuejs.org/guide/composition-api-setup.html#accessing-component-properties. You should be able to use route() normally inside the template part of the component, but to use it in setup() I think you'd have to import it and set it up manually each time, something like this (pseudo-code, I didn't try to run this):

<script>
import route from `ziggy`;
import Ziggy from `./ziggy.js`;

export default {
    setup() {
        route('home', undefined, undefined, Ziggy); // https://my-app.test
    }
}
</script>

Can you try that and see if it works?

sprklinginfo commented 3 years ago

thanks for the suggestion, @bakerkretzmar. Unfortunately, it doesn't work. I am trying to use composition API on all of my components as much as I can. In the Laravel Breeze starter kit, route() is imported as a mixin, so I probably have to use both options API and composition API if I want to use route() in the Githubissues.

  • Githubissues is a development platform for aggregating issues.