Even if we implement all of the cool features that Yii2 bring to the table, sometimes we can encounter problems such as slowness, particularly if the page has a lot of HTML rendered and requires a lot of interactivity with end users. When this happens, we should consider using some of the modern JavaScript frameworks.
Rewriting the entire application into a JS framework can be unacceptable for our clients in terms of finance, thus we have to find different approaches. One possible solution is to move the problematic parts of the page from server to our browser, and provide high speed of execution by serving that data only from API without re-rendering the entire page. One of the best JS frameworks that can accomplish this is Vue.
Vue is a progressive JS framework. This means that if you have an existing server side rendered application, you can plug Vue into just one part of your application which needs a richer and more interactive experience. Vue is lightweight and designed to be easy to integrate inside existing applications. In this blog post, we will discuss how to integrate Vue inside just one part of an existing Yii2 application.
To start off, let’s imagine that we are using a basic template of a Yii2 application and we want to replace the main container of the page with application served in Vue. In order to build Vue, we need to have Node and NPM installed. Node installation depends on the operating system you are running your application on.
The first thing is to cd into root folder of our application and initialize npm by running:
1npm init
We will be prompted to enter some information regarding the project. This is not very important at the moment so we can simply stick with the default values for now. Upon successful creation of the package.json file we can add Vue package:
1npm install --save vue
Since Vue application requires build file to run properly, we should find the tool that will serve this purpose. One of the most popular tools that takes your development assets and combines them into a bundle is called Webpack. In our case, Webpack will build all of our components into a single JS file which can be injected into Yii2 application assets. Let’s install it by executing the following command:
1npm install --save-dev webpack webpack-cli
Along with Webpack, we must install webpack-cli, a tool used to run Webpack on the command line. Webpack and webpack-cli packages are needed for development purposes and because of this, we will append –save-dev flag during installation.
Once that’s done, create src folder inside Yii2 application root and put Vue entry point script along with App component. Entry point app.js script should look like this:
1import Vue from 'vue';
2import App from './App.vue';
3
4new Vue({
5 el: '#app',
6 render: h => h(App)
7})
The piece of code below will pull the main application component and render it into the DOM element with id “app”:
1// App.vue
2<template>
3 <div>
4 <h1>{{ text }}</h1>
5 </div>
6</template>
7
8<script>
9 export default {
10 name: "App",
11 data: function () {
12 return {
13 text: 'This part of application is rendered in Vue.'
14 }
15 }
16}
17</script>
All packages needed for building up Vue code are exposed below:
1npm install --save-dev vue-loader vue-template-compiler vue-style-loader css-loader style-loader
In the root of our project, we will create webpack.config.js file. This file will contain all configuration that is needed for Webpack.
1// webpack.config.js
2const path = require('path');
3const webpack = require( 'webpack' );
4
5const PATHS = {
6 source: path.join(__dirname, 'src'),
7 build: path.join(__dirname, 'web')
8};
9
10const { VueLoaderPlugin } = require('vue-loader');
11
12module.exports = (env, argv) => {
13 let config = {
14 production: argv.mode === 'production'
15 };
16
17 return {
18 mode: 'development',
19 entry: [
20 './src/app.js'
21 ],
22 output: {
23 path: PATHS.build,
24 filename: config.production ? 'app.min.js' : 'app.js'
25 },
26 module: {
27 rules: [
28 {
29 test: /\.vue$/,
30 use: 'vue-loader'
31 },
32 {
33 test: /\.css$/,
34 loader: ['style-loader', 'css-loader']
35 }
36 ]
37 },
38 plugins: [
39 new VueLoaderPlugin()
40 ]
41 };
42};
Module section contains loaders needed for building code of Vue component. Bundled Vue application is almost ready - there are only two more scripts that need to be added inside package.json file in order to bundle it in development and production environments. We should update scripts sections of package.json file to the following:
1"scripts": {
2 "dev": "webpack --config webpack.config.js",
3 "prod": "webpack --config webpack.config.js --optimize-minimize --mode production"
4 }
Now that we have everything in place for building Vue application in js file, lets run “npm run dev“. This command will bundle up code and generate script for development purposes that can be included into the Yii2 application bundle.
In my personal opinion, it is much cleaner to create a separate layout file layout.php and VueAssets.php asset bundle class and avoid inclusion of Vue bundle in other pages which don’t need it. Action that will render Vue container page is represented below along with other Yii2 based code needed for proper functioning of Vue app inside Yii2 project structure:
1// VueAssets.php
2class VueAssets extends yii\web\AssetBundle
3{
4 public $basePath = '@webroot';
5 public $baseUrl = '@web';
6
7 public function init()
8 {
9 parent::init();
10
11 $this->js[] = YII_ENV === 'local' ? 'app.js' : 'app.min.js';
12 }
13}
14
15// IndexController.php
16public function actionVue()
17{
18 // set the specific layout for pages that will render vue
19 $this->layout = 'vue_main';
20
21 // override bundle configuration if needed
22 Yii::$app->assetManager->bundles = [];
23
24 // render page
25 return $this->render('vue_page');
26}
27
28// vue_main.php
29$bundle = VueAssets::register($this);
To see these steps in full implementation, please visit: https://github.com/srdjan92/yii2-vue-basic
Accelerate Your Career with 2am.tech
Join our team and collaborate with top tech professionals on cutting-edge projects, shaping the future of software development with your creativity and expertise.
Open Positions