This website uses cookies

Our website, platform and/or any sub domains use cookies to understand how you use our services, and to improve both your experience and our marketing relevance.

📣 Join the live AMA session with Adam Silverstein on open source and WordPress core! Register Now →

Getting Started with Vue.js in Symfony

Updated on June 2, 2021

6 Min Read

Virtually all web application projects, now require a reasonable portion of logic to be executed on the client side. Symfony as a set of reusable PHP components and a web application framework is not exempted from this trend.

As a PHP developer who uses Symfony regularly, I have had a hard time choosing from the numerous JavaScript frontend frameworks available in the market. I had to pick one from the top rated JavaScript frameworks including Angular, React, Vue and Aurelia.

Vue.js in Symfony
1. Symfony Remains Neutral
2. So Why Vue?
3. The Importance of Frontend
4. Prerequisites
5. Create A Symfony Application
6. Create the Route and Controller
7. Install Vue and its Dependencies
8. Configure Vue-loader
9. Create the Vue Component
10. Show Vue Component Content
11. Final Note

Symfony Remains Neutral

With the whole hype around which JavaScript framework works best for development, Symfony as a framework remains neutral when it comes to making a choice of framework that powers the client side logic and activities in web applications. In effect, Symfony doesn’t have a favorite JavaScript framework.

In this article, I will go over the process of enabling and configuring Vue.js within Symfony applications. Part of this process is covered in the official Symfony documentation. But since the docs can be boring at times, I decided to take a practical approach in which I will:

  • Create a Symfony 4 application
  • Install Vue.js and the dependencies
  • Require and process .vue files correctly
  • Create my first Vue component.

So Why Vue?

To begin, let me state that I have no personal favorites in JavaScript frameworks. I simply use the right tool for the project’s requirements and desired functionalities.

Arguably, Vue is one of the best frontend library available today. It is a lightweight and progressive framework that is an ideal fit for all projects.

You Might Also Like: Learn How to Enable Pagination in Laravel With Vue

The Importance of Frontend

I get this question from web developers a lot. A common concern is the addition of complexity to an already complex application. Frontend frameworks like Vue help abstract the complexity and basic application client side logic of any project. This enforces good design patterns and helps create reasonably reusable components. In just few lines of code, you can build a single page application, easily manipulate DOM and make AJAX call to the backend service without hassle.

Get Your VueJS Handbook Now

Simple enter your email address and get the download link in your Inbox.

Thank You

Your Ebook is on it’s Way to Your Inbox.

Prerequisites

I will build a Symfony application that uses Vue as a frontend framework. At first, this application will run locally in the development environment. Afterward, it can be easily hosted and uploaded to any best PHP hosting.

To get the best out of this tutorial, a reasonable knowledge of PHP, JavaScript and Object Oriented Programming is advised.

Create A Symfony Application

To start, use composer to quickly set up a new Symfony project. Alternatively, set up a Cloudways account to launch a server and follow this tutorial to set up a Symfony 4 project in just a few minutes.

Symfony 4 comes with Flex, a new way of creating web applications with ease by automating the addition and removal of bundles.

Launch the terminal and use the following command to set up the Symfony app with all the dependencies:

composer create-project symfony/website-skeleton vue-symfony

The above command creates a new project directory called vue-symfony and a few dependencies for a standard Symfony application are downloaded as well.

 

Before setting up Vue.js, lets install a web server. Change directory into the newly created project and run a command to install the web server in the terminal:

cd vue-symfony

composer require server -- dev

 

Next, start the server with:

php bin/console server:run

Navigate to http://localhost:8000/ :

Create the Route and Controller

In the terminal, create a new controller using the following command:

php bin/console make:controller Default

This will create a new controller class named DefaultController and template file for it. Locate the controller and replace the contents of the index() method with:

php hosting signup

Replace the contents of the index() method with:

/**
* @Route("/", name="default")
*/
public function index()
{
   return $this->render('index.html.twig');

}

Next, create a new file .vue-symfony/templates/index.html.twig within the templates folder.

{% extends 'base.html.twig' %}

{% block body %}

   <h3>My Symfony 4 sample project</h3>

{% endblock %}

Go back and restart the server:

Install Vue and its Dependencies

With the introduction of Encore, asset management has become a piece of cake. This asset management tool uses webpack and allows powerful CSS and JavaScript processing, combination, and minification. Before proceeding, ensure that you have Node.js and Yarn package manager installed on your machine.

Using yarn, install Vue and the dependencies.

yarn add --dev vue [email protected] vue-template-compiler

Configure Vue-loader

vue-loader needs to be activated in webpack.config.js. Leave other default settings alone and just enable vue loader through the following code snippet:

var Encore = require('@symfony/webpack-encore'); Encore
   .setOutputPath('public/build/')
   .setPublicPath('/build')
   .cleanupOutputBeforeBuild()
   .enableSourceMaps(!Encore.isProduction())
   .addEntry('js/app', './assets/js/app.js')
   // .addStyleEntry('css/app', './assets/css/app.scss')
   // .enableSassLoader()
   // .autoProvidejQuery()


   // Enable Vue loader
   .enableVueLoader()
;

module.exports = Encore.getWebpackConfig();

Webpack Encore expects an entry point. For this, create a subdirectory named called  js  within assets folder and then add a app.js file inside of it.

// assets/js/app.js
import Vue from 'vue';

import Example from './components/Example'

/**
* Create a fresh Vue Application instance
*/
new Vue({
  el: '#app',
  components: {Example}
});

In the above code snippet, I first imported Vue and Example component. Next, I created an instance of Vue, pass an element where Vue will attach itself to and register the Example component so that it can be accessible.

Create the Vue Component

I will use Vue.js as a widget and include it within Twig template to bring more reactivity to the Symfony application. This is one of the numerous ways of using Vue.js.

Before I compile .vue files, I will create the component. For this, create a new folder assets/js/components and a new component file named  assets/js/components/Example.vue

<template>
   <div>
       <p>This is an example of a new components in VueJs</p>
   </div>
</template>

<script>
   export default {
       name: "example"
   }
</script>

<style scoped>

</style>

Next, I can compile the asset that would be used in the Symfony template and watch the changes by using the following command:

yarn run encore dev --watch

Open the base twig template .vue-symfony/templates/base.html.twig and include the compiled JavaScript files into the base template that would be used in the application.

<!DOCTYPE html>
<html>
   <head>
       <meta charset="UTF-8">
       <title>{% block title %}Welcome!{% endblock %}</title>
       {% block stylesheets %}
           <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
       {% endblock %}
   </head>
   <body>
   <div id="app">
       {% block body %}{% endblock %}
   </div>

   {% block javascripts %}
       <script src="{{ asset('build/js/app.js') }}"></script>
   {% endblock %}

   </body>
</html>

Show Vue Component Content

Earlier, I created a Vue.js component and registered it for use in the application. This is made possible by including  the custom tag for the newly created component. Edit .vue-symfony/templates/index.html.twig and include the Example component.

{% extends 'base.html.twig' %}
{% block body %}

   <div class="text-center">
       <h3>My Symfony 4 sample project</h3>

       <div class="jumbotron text-center">
           <example></example>
       </div>
   </div>

{% endblock %}

Navigate to the local server (at port 8000) and check out the result:

Final Note

I hope this article has giving you enough enlightenment on how to get started with Vue.js in Symfony apps. So the next time you are faced with the choice of the picking a frontend JavaScript framework, use the tricks you have learned here to get an easy start. The code of this article can be found at Github.

Disclaimer: The opinions and views presented in this article are author’s own, and does not reflect the official policy and views of Cloudways.

Author of the Post: This post is contributed by Olususi Oluyemi. He is a tech enthusiast, programming freak and a web development junkie who loves to embrace new technology. You can find him on yemiwebby.

Share your opinion in the comment section. COMMENT NOW

Share This Article

Olususi k Oluyemi

A tech enthusiast, programming freak and a web development junkie who loves to embrace new technology.

×

Get Our Newsletter
Be the first to get the latest updates and tutorials.

Thankyou for Subscribing Us!

×

Webinar: How to Get 100% Scores on Core Web Vitals

Join Joe Williams & Aleksandar Savkovic on 29th of March, 2021.

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

Want to Experience the Cloudways Platform in Its Full Glory?

Take a FREE guided tour of Cloudways and see for yourself how easily you can manage your server & apps on the leading cloud-hosting platform.

Start my tour

CYBER WEEK SAVINGS

  • 0

    Days

  • 0

    Hours

  • 0

    Mints

  • 0

    Sec

GET OFFER

For 4 Months &
40 Free Migrations

For 4 Months &
40 Free Migrations

Upgrade Now