Using named API routes in separated Vue CLI generated Applications
This tutorial will teach you how to use named, and exposed routes via Symfony FOSJsRoutingBundle in separated Vue CLI generated Applications.
Where to use
The main problem is how to make it work in a completely separated Vue.js application which is generated by Vue CLI (not embedded/served by a twig template).
PimCore is using FOSJsRoutingBundle by default (ExtJS admin components use it), and there is no need for any extra installation via composer.
We will explain two approaches:
Importing js files directly to Vue.js application code: The application needs to be inside the main codebase (PimCore project), and JSON — which contains routes configuration — needs to be generated one ach API change.
Thoughts on solutions are that while the first one may have a bit cleaner code, the second solution is a bit better approach since you can use it anywhere and don’t need to take care about routes configuration in JSON file.
Before anything frontend related, let’s create a test API route (only for example):
The first approach (Vue.js App is inside PimCore project codebase):
What you need to take care of is that JSON — which contains routes — must be updated/generated on each API change via:
The second approach (Vue.js App is outside the PimCore project codebase):
First, create two environment files (.env and .env.local) inside Vue.js application root. More on them here.
We will use one environment variable for our PimCore served host (both .env and .env.local):
Environment variables prefixed with “VUE_APP” are automatically inserted so we can use them in our app. Let’s add script tags with paths to files to <head> inside index.html:
Take care that we’re generating routes with the absolute URLs option set to “true” since our Vue.js application will probably be served on another domain than the main PimCore application.
Does it work?
To test it, create some named route and set the exposed option to true. After that, simply generate that route by its name. The Browser or Hot module reload (HMR) will refresh the browser with new code and data, and you should see it immediately.
We hope you find this helpful, but don't hesitate to contact us if you have any additional questions. Happy coding! :)