tighten / ziggy

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

ziggy-js: t.route is not a function - Vue3/Vite + Inertia #536

Closed jjjrmy closed 2 years ago

jjjrmy commented 2 years ago

Ziggy version

v1.4.4

Description

I am using ziggy-js for a SPA, and imported it as show in the documentation here: https://github.com/tighten/ziggy#vue I'm getting the error vendor.f1f20a1a.js:4 TypeError: t.route is not a function I can't figure out how to include the Ziggy Vue in my application.

Ziggy call and context

import { createApp, h } from 'vue';
import { createInertiaApp } from '@inertiajs/inertia-vue3'

import { ZiggyVue } from 'ziggy-js/dist/vue.js';
import { Ziggy } from './ziggy';

createInertiaApp({
      resolve: name => import(`./views/${name}.vue`),
      setup({ el, App, props, plugin }) {
        createApp({ render: () => h(App, props) })
          .use(plugin, ZiggyVue, Ziggy)
          .mount(el)
      },
    })
<Link :href="route('createContact')">Create Contact</a>

Ziggy configuration

{
    "url": "https://pingcrm.test",
    "port": null,
    "defaults": {},
    "routes": {
        "index": {
            "uri": "/",
            "methods": [
                "GET",
                "HEAD"
            ]
        },
        "showContact": {
            "uri": "showContact/{contact}",
            "methods": [
                "GET",
                "HEAD"
            ]
        },
        "createContact": {
            "uri": "createContact",
            "methods": [
                "GET",
                "POST",
                "HEAD"
            ]
        },
        "login": {
            "uri": "login",
            "methods": [
                "GET",
                "HEAD"
            ]
        },
        "logout": {
            "uri": "logout",
            "methods": [
                "POST"
            ]
        },
        "register": {
            "uri": "register",
            "methods": [
                "GET",
                "HEAD"
            ]
        },
    }
}
bakerkretzmar commented 2 years ago

Each Vue plugin needs its own .use(), and the configuration object to pass to the plugin is the second argument. This should fix it:

-          .use(plugin, ZiggyVue, Ziggy)
+          .use(plugin)
+          .use(ZiggyVue, Ziggy)
jjjrmy commented 2 years ago

@bakerkretzmar Just curious, is this any different than:

import route from 'ziggy-js';
const ZiggyRoutes = await fetch('https://.../api/routes').then(x => x.json());
const ZiggyRouter = (name, params) => route(name, params, true, ZiggyRoutes);

...

createApp({ render: () => h(App, props) })
          .mixin({ methods: { route: ZiggyRouter } })
bakerkretzmar commented 2 years ago

Not really no, the Vue plugin is basically just that mixin. Fetching the routes from an endpoint like that is probably going to be a lot slower than importing them from a generated ziggy.js file though.