Advanced Server-Side Rendering With Laravel & Vue

Advanced Server-Side Rendering With Laravel & Vue

Advanced Server-Side Rendering With Laravel & Vue. A few weeks ago I wrote a tutorial on the new Vue server-side rendering capabilities for Laravel. That tutorial mostly focused on the set up of SSR in a Laravel environment and so I only had time to demonstrate a simple “Hello World” app with no significant features.

Now I want to build on that previous tutorial and demonstrate how to server render a Vue app that includes multiple pages with Vue Router, since most of your Laravel projects will have more than one page.

You can get the completed code for this tutorial here on Github.

Note: this article was originally posted here on the Vue.js Developers blog on 2017/11/27### Installation

This tutorial will extend the app I built in the previous article, Server-Side Rendering With Laravel & Vue.js 2.5. Make sure you’re familiar with how it works and have a suitable development environment set up i.e. with the php-v8js extension installed.

If you don’t have that code, clone it and set it up:

$ git clone https://github.com/anthonygore/vue-js-laravel-ssr
$ cd vue-js-laravel-ssr
$ cp .env.example .env
$ composer install
$ npm i

Then install Vue Router:

$ npm i --save-dev vue-router

Router module

We’ll begin by creating a file for our router configuration that exports an instance of the router for use in the app.

I’ve made up some sample routes with each displaying a component generated from the method pageComponent. This factory method returns a simple component that does nothing more than display the name of the page. This is all we need to prove SSR routing works.

resources/assets/js/router.js

import Vue from 'vue'
import Router from 'vue-router'
Vue.use(Router);
function PageComponent(name) {
 return {
   render: h => h('h3', `Hello from the ${name} page`)
 };
}
export default new Router({
  mode: 'history',
  routes: [
    { path: '/', component: PageComponent('Home'), name: 'home' },
    { path: '/about', component: PageComponent('About'), name: 'about' },
    { path: '/contact', component: PageComponent('Contact'), name: 'contact' }
  ]
});

router.js

In the main app file we’ll now import the router module and add it to the app, just as you would in any Vue project. The app instance is then exported for use in the client and server entry files.

resources/assets/js/app.js

import App from './components/App.vue';
import Vue from 'vue';
import router from './router'
export default new Vue({
  router,
  render: h => h(App)
});

app.js

Laravel routes

Note that our Vue Router instance is in history mode, so routes will fallback to the server when a sub-page is refreshed or loaded from the navigation bar.

This means that any route that we created in the front-end app also needs to be created on the server side. They can all point to the same controller method get:

routes/web.php

<?php
Route::get('/', '[email protected]');
Route::get('/about', '[email protected]');
Route::get('/contact', '[email protected]');

web.php

Controller

Now we need to set up multi-page SSR in the controller. This is a modification of the logic in the base app, so make sure you’re familiar with how that worked.

To SSR a multi-page app, we need to tell the Vue server app (as defined in entry-server.js) what the current URL being requested is. This will ensure that when the app loads in the sandbox, it’s displaying the correct page component.

To do this we pass the URL i.e. $request->path() through to the render method from the get method. We then store the URL in a global JavaScript variable url that will be accessible from the Vue server app when it runs in the sandbox.

app/Http/Controllers/AppController.php

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\File;
use Illuminate\Routing\Route;
class AppController extends Controller
{
  private function render($path) {
    $renderer_source = File::get(base_path('node_modules/vue-server-renderer/basic.js'));
    $app_source = File::get(public_path('js/entry-server.js'));
    $v8 = new \V8Js();
    ob_start();
    $js = 
<<<EOT
var process = { env: { VUE_ENV: "server", NODE_ENV: "production" } }; 
this.global = { process: process }; 
var url = "$path";
EOT;
    $v8->executeString($js);
    $v8->executeString($renderer_source);
    $v8->executeString($app_source);
    return ob_get_clean();
  }
  public function get(Request $request) {
    $ssr = $this->render($request->path());
    return view('app', ['ssr' => $ssr]);
  }
}

AppController.php

Vue server app

The last major step is to modify the Vue server app so that we can programmatically set the URL rather than waiting for a user to do it.

The logic for doing this is inside the Promise callback function. Here’s what it does:

  • The router is set to the correct URL by pushing the global variable url
  • When the router is ready, we see if any page components are being displayed as a result of this push, telling us the route is valid. If not, we throw a 404. If so, we return the app instance.

A Promise is used because the router loads asynchronously. Once this Promise resolves, we can use the server renderer method renderVueComponentToString to SSR the instance and finally use print to return the output back to our Laravel environment.

resources/assets/js/entry-server.js

import app from './app'
import router from './router';
new Promise((resolve, reject) => {
  router.push(url);
  router.onReady(() => {
    const matchedComponents = router.getMatchedComponents();
    if (!matchedComponents.length) {
      return reject({ code: 404 });
    }
    resolve(app);
  }, reject);
})
  .then(app => {
    renderVueComponentToString(app, (err, res) => {
      print(res);
    });
  })
  .catch((err) => {
    print(err);
  });

entry-server.js

App file

The SSR logic for the multi-page app is now complete. Let’s create some router links in the page so we can test the app in a browser:

resources/asset/js/components/App.vue

<template>
  <div id="app">
    <h1>{{ title }}</h1>
    <router-view></router-view>
    <router-link :to="{ name: 'about' }">About</router-link>
    <router-link :to="{ name: 'contact' }">Contact</router-link>
  </div>
</template>
<script>
  export default {
    data() {
      return {
        title: 'Welcome To My Site'
      }
    }
  }
</script>

app.vue

Loading the home page look like this:

The real test is visiting a route in the navigation bar so the server routes handle the request and hopefully SSR the app. To do so, visit [http://localhost:9000/about](http://localhost:9000/about "http://localhost:9000/about") and inspect the source markup. As you can see, it includes the rendered app at the correct URL:

Recommended Courses:

Curso de VueJS 2

Vuejs 2 + Vuex con TypeScript Nivel PRO

Curso de Vuejs 2, Cognito y GraphQL

Learn VueJS from Scratch: The Complete 1 Hour Crash Course!

SSR con Vuejs, Vuex y Quasar Framework

10 Best Vue Icon Component For Your Vue.js App

10 Best Vue Icon Component For Your Vue.js App

In this article, I will collect 10 Vue icon component to bring more interactivity, better UI design to your Vue application.

Icons are the vital element of the user interface of the product enabling successful and effective interaction with it. In this article, I will collect 10 Vue icon component to bring more interactivity, better UI design to your Vue application.

1. Animated SweetAlert Icons for Vue

A clean and simple Vue wrapper for SweetAlert's fantastic status icons. This wrapper is intended for users who are interested in just the icons. For the standard SweetAlert modal with all of its bells and whistles, you should probably use Vue-SweetAlert 2

Demo: https://vue-sweetalert-icons.netlify.com/

Download: https://github.com/JorgenVatle/vue-sweetalert-icons/archive/master.zip

2. vue-svg-transition

Create 2-state, SVG-powered animated icons.

Demo: https://codesandbox.io/s/6v20q76xwr

Download: https://github.com/kai-oswald/vue-svg-transition/archive/master.zip

3. Vue-Awesome

Awesome SVG icon component for Vue.js, with built-in Font Awesome icons.

Demo: https://justineo.github.io/vue-awesome/demo/

Download: https://github.com/Justineo/vue-awesome/archive/master.zip

4. vue-transitioning-result-icon

Transitioning Result Icon for Vue.js

A scalable result icon (SVG) that transitions the state change, that is the SVG shape change is transitioned as well as the color. Demonstration can be found here.

A transitioning (color and SVG) result icon (error or success) for Vue.

Demo: https://transitioning-result-icon.dexmo-hq.com/

Download: https://github.com/dexmo007/vue-transitioning-result-icon/archive/master.zip

5. vue-zondicons

Easily add Zondicon icons to your vue web project.

Demo: http://www.zondicons.com/icons.html

Download: https://github.com/TerryMooreII/vue-zondicons/archive/master.zip

6. vicon

Vicon is an simple iconfont componenet for vue.

iconfont
iconfont is a Vector Icon Management & Communication Platform made by Alimama MUX.

Download: https://github.com/Lt0/vicon/archive/master.zip

7. vue-svgicon

A tool to create svg icon components. (vue 2.x)

Demo: https://mmf-fe.github.io/vue-svgicon/v3/

Download: https://github.com/MMF-FE/vue-svgicon/archive/master.zip

8. vue-material-design-icons

This library is a collection of Vue single-file components to render Material Design Icons, sourced from the MaterialDesign project. It also includes some CSS that helps make the scaling of the icons a little easier.

Demo: https://gitlab.com/robcresswell/vue-material-design-icons

Download: https://gitlab.com/robcresswell/vue-material-design-icons/tree/master

9. vue-ionicons

Vue Icon Set Components from Ionic Team

Design Icons, sourced from the Ionicons project.

Demo: https://mazipan.github.io/vue-ionicons/

Download: https://github.com/mazipan/vue-ionicons/archive/master.zip

10. vue-ico

Dead easy, Google Material Icons for Vue.

This package's aim is to get icons into your Vue.js project as quick as possible, at the cost of all the bells and whistles.

Demo: https://material.io/resources/icons/?style=baseline

Download: https://github.com/paulcollett/vue-ico/archive/master.zip

I hope you like them!

Collection of 10 Vue Markdown Component for Vue.js App in 2020

Collection of 10 Vue Markdown Component for Vue.js App in 2020

Markdown is a way to style text on the web. The 10 Vue markdown components below will give you a clear view.

Markdown is a way to style text on the web. You control the display of the document; formatting words as bold or italic, adding images, and creating lists are just a few of the things we can do with Markdown.

The 10 Vue markdown components below will give you a clear view.

1. Vue Showdown

Use showdown as a Vue component.

View Demo

Download Source

2. showdown-markdown-editor

A markdown editor using codemirror and previewer using showdown for Vue.js.

View Demo

Download Source

3. markdown-it-vue

The vue lib for markdown-it.

View Demo

Download Source

4. perfect-markdown

perfect-markdown is a markdown editor based on Vue & markdown-it. The core is inspired by the implementation of mavonEditor, so perfect-markdown has almost all of the functions of mavonEditor. What's more, perfect-markdown also extends some features based on mavonEditor.

View Demo

Download Source

5. v-markdown-editor

Vue.js Markdown Editor component.

View Demo

Download Source

6. markdown-to-vue-loader

Markdown to Vue component loader for Webpack.

View Demo

Download Source

7. fo-markdown-note Component for Vue.js

fo-markdown-note is a Vue.js component that provides a simple Markdown editor that can be included in your Vue.js project.

fo-markdown-note is a thin Vue.js wrapper around the SimpleMDE Markdown editor JavaScript control.

View Demo

Download Source

8. Vue-SimpleMDE

Markdown Editor component for Vue.js. Support both vue1.0 & vue2.0

View Demo

Download Source

9. mavonEditor

A nice vue.js markdown editor. Support WYSIWYG editing mode, reading mode and so on.

View Demo

Download Source

10. vue-markdown

A Powerful and Highspeed Markdown Parser for Vue.

View Demo

Download Source

Thank for read!

Collection of 15 Vue Input Component for Your Vue.js App

Collection of 15 Vue Input Component for Your Vue.js App

Vue input component gives you a baseline to create your own custom inputs. It consists of a prepend/append slot, messages, and a default slot. In this article I will share 15 Vue input components to you.

Vue input component gives you a baseline to create your own custom inputs. It consists of a prepend/append slot, messages, and a default slot. In this article I will share 15 Vue input components to you.

1. Maska
  • No dependencies
  • Small size (~2 Kb gziped)
  • Ability to define custom tokens
  • Supports repeat symbols and dynamic masks
  • Works on any input (custom or native)

Demo

Download


2. v-range-flyout

A vue component that wraps a input type=number with a customizable range slider flyout with 2-way binding.

Demo

Download


3. vue-tel-input

International Telephone Input with Vue.

Demo

Download


4. Restricted Input

Allow restricted character sets in input elements.

Features

  • Disallow arbitrary characters based on patterns
  • Maintains caret position
  • Format/Update on paste
  • Works in IE11+

Demo

Download


5. Vue Currency Input

The Vue Currency Input plugin allows an easy input of currency formatted numbers.

Demo

Download


6. vue-fields

Input components for vue.js.

Demo

Download


7. vue-material-input

Simple example of issue I am seeing with input labels.

Demo

Download


8. vue-tribute

A Vue.js wrapper for Zurb's Tribute library for native @mentions.

Demo

Download


9. vue-number-smarty

Number input with rich functionality for Vue.js.

Features

  • integer/float
  • signed/unsigned
  • step size
  • increment/decrement value by scrolling when focused
  • align variants
  • min and max boundaries
  • max length of integer part (only for float type)
  • max length of float part (only for float type)
  • max length of string
  • error state
  • readonly state
  • theme options

Demo

Download


10. Vue input mask

Super tiny input mask library for vue.js based on PureMask.js (~2kb) exposed as directive. No dependencies.

Demo

Download


11. vue-r-mask

mask directive for vue.js

  • Template similar to javascript regular expression. /\d{2}/
  • Directive useful for your own input or textarea.
  • Arbitrary number of digits in template /\d{1,10}/

Demo

Download


12. Vue IP

An ip address input with port and material design support.

Demo

Download


13. v-money Mask for Vue.js

Tiny input/directive mask for currency

Features

  • Lightweight (<2KB gzipped)
  • Dependency free
  • Mobile support
  • Component or Directive flavors
  • Accept copy/paste
  • Editable

Demo

Download


14. Vue Masked Input

Dead simple masked input component for Vue.js 2.X. Based on inputmask-core.

Demo

Download


15. VueJS input component

Mobile & Desktop friendly VueJS input component
Features used
CSS variables
Vue's transition-group
Flexbox

Demo


I hope you like them!