Symfony Routes in Vue.js (SPA)
This article discusses how to pass URLs from Vue.js to Symfony with simple rerouting options. We discuss what each platform is and how to connect them.
Join the DZone community and get the full member experience.Join For Free
With a new project (or more like an extension of an already existing project), I started to wonder if there is actually a way to share Symfony routes in Vue.js. I’ve already in a big, over 2 years old private project, in which the urls are simply hardcoded in the frontend — with this I wanted to find a way out to replicate the routing in the Vue.js.
Actually the solution for this is pretty simple, and allows to easily replicate the url generating logic available in php:
Handling Routes for Vue.js
The difference in Routes Structure
The foremost important difference between Symfony and Vue.js routes is the way that parameters in URLs are handled.
While Symfony uses this annotation:
Vue.js uses this one:
Generating Routes for Vue.js
All available routes can be loaded and afterwards inserted into the
json file, which is a perfect solution to read later on with Vue.js. For this, I’ve created a Symfony Command:
Afterwards all that has to be done is loading the generated file in the Typescript Class:
and adding a method to load the url by route name and to replace the provided parameters:
It’s possible to make things even better just by adding the constants in Typescript (static readonly):
If Symfony is properly configured, and the route file is
json instead of
yaml/yml then the routes loading will work "out-of-box." However, in my case and as I see in other people's projects the,
Annotation is the favorite way to define a route.
- Unified routes in frontend and backend.
- Necessity to call the command upon adding new routes.
Published at DZone with permission of Dariusz Włodarczyk. See the original article here.
Opinions expressed by DZone contributors are their own.