Using vue.js with concrete5

This is a community-contributed tutorial. This tutorial is over a year old and may not apply to your version of Concrete CMS.
Apr 17, 2019

In this tutorial we'll create a new block type that uses vue.js to collect data, and post data back to the server via ajax.

Here we'll use jQuery to perform the ajax call since it's bundled with concrete5, but of course you can use any other library (like axios for example).

Block controller

The controller.php file of the block type:

<?php

namespace Application\Block\MyBlock;

use Concrete\Core\Block\BlockController;
use Concrete\Core\Error\UserMessageException;
use Concrete\Core\Http\ResponseFactoryInterface;
use Concrete\Core\User\User;

defined('C5_EXECUTE') or die('Access denied.');

class Controller extends BlockController
{
    /**
     * Get the name of the block type.
     *
     * @return string
     */
    public function getBlockTypeName()
    {
        return t('My Block');
    }

    /**
     * Get the description of the block type.
     *
     * @return string
     */
    public function getBlockTypeDescription()
    {
        return t('A sample block type to demonstrate how you can use vue.js in concrete5.');
    }

    /**
     * {@inheritdoc}
     *
     * @see \Concrete\Core\Block\BlockController::registerViewAssets()
     */
    public function registerViewAssets($outputContent = '')
    {
        $this->requireAsset('javascript', 'jquery');
        $this->requireAsset('javascript', 'vue');
    }

    public function view()
    {
        $user = new User();
        $token = $this->app->make('token');
        $this->set('dataForVue', [
            'userName' => $user->isActive() ? $user->getUserName() : t('guest'),
            'busy' => false,
            'data' => [
                $token::DEFAULT_TOKEN_NAME => $token->generate('my-block-submit'),
                'age' => null,
            ],
        ]);
        $this->set('uniqueBlockIdentifier', $this->getUniqueBlockIdentifier());
    }

    public function action_submit()
    {
        $token = $this->app->make('token');
        if (!$token->validate('my-block-submit')) {
            throw new UserMessageException($token->getErrorMessage());
        }
        $post = $this->request->request;
        $age = (int) $post->get('age');
        if ($age < 1 || $age > 150) {
            throw new UserMessageException(t('The age does not seems correct'));
        }

        return $this->app->make(ResponseFactoryInterface::class)->json([
            'message' => t('Well done!'),
        ]);
    }

    /**
     * @return int
     */
    private function getUniqueBlockIdentifier()
    {
        $bID = null;
        $b = $this->getBlockObject();
        if ($b) {
            $pb = $b->getProxyBlock();
            if ($pb) {
                $bID = $pb->getBlockID();
            }
        }

        return (int) ($bID ?: $this->bID);
    }
}

The getBlockTypeName() and getBlockTypeDescription() methods are the concrete5 way to give a name and a description to a block type.

The registerViewAssets() method instructs concrete5 that we'll need vue and jquery in the block type view.

The view() method prepares the data for the view. In this case we create an array named $dataForView, and define $uniqueBlockIdentifier that contains an integer that uniquely identifies the block instance (returned by the uniqueBlockIdentifier() method).

action_submit() is the method that will receive the data via ajax. In this example it simply protects agains CSRF attacks, checks that the data is valid, and send back a message to the client.

Block view

Here's the view.php file of the block type:

<?php

defined('C5_EXECUTE') or die('Access denied.');

/** @var Application\Block\MyBlock\Controller $controller */
/** @var array $dataForVue */
/** @var int $uniqueBlockIdentifier */

?>

<div id="my-block-<?= $uniqueBlockIdentifier ?>">
    <form v-on:submit.prevent="save">
        <?= t('Hello %s', '{{ userName }}') ?><br />
        <?= t('Your age?') ?><br />
        <input type="number" min="1" max="150" v-model="data.age" required="required" /><br />
        <input type="submit" value="<?= t('Save') ?>" v-bind:disabled="busy" />
    </form>
</div>

<script>
$(document).ready(function() {
    var vue;

    vue = new Vue({
        el: '#my-block-<?= $uniqueBlockIdentifier ?>',
        data: function() {
            return <?= json_encode($dataForVue) ?>;
        },
        methods: {
            save: function() {
                if (this.busy) {
                    return;
                }
                this.busy = true;
                $.ajax({
                    dataType: 'json',
                    method: 'POST',
                    url: <?= json_encode((string) $controller->getActionURL('submit')) ?>,
                    data: this.data
                })
                .done(function (data) {
                    window.alert(data.message);
                })
                .fail(function (xhr, status, error) {
                    if (xhr.responseJSON && xhr.responseJSON.errors && xhr.responseJSON.errors.length > 0) {
                        window.alert(xhr.responseJSON.errors.join('\n'));
                    } else {
                        window.alert(status);
                    }
                })
                .always(function() {
                    vue.busy = false;
                });
            }
        }
    });
});
</script>

The above code defines the <div> node that will contain the vue application. It prints out the current user name (contained in the userName property of the vue app) and it asks for an integer (bound to the data.age property of the app).

When the user hit the submit button, the save method of the vue app performs an ajax call that sends all the values contained in the data property), and correctly handles errors in case of problems.

Recent Tutorials
Using the Concrete Migration Tool Addon
Apr 27, 2023

How to use the Concrete CMS Migration Tool

How To Add Page Last Updated To Your Concrete CMS Pages
Mar 7, 2023

Concrete CMS has a page attribute you can add to a global area called "Page Date Modified." Here's how to add it

How To Exclude Subpages from Navigation
Dec 24, 2022

How to exclude subpages from navigation - useful for a news or blog link in your main navigation where you don't want all the subpages to appear in a drop down menu.

How Can I Change The Maximum Size Of Uploaded files
Dec 13, 2022

This tutorial explains how to update your php settings.

Updating Concrete Themes from Version 8 to Version 9
Nov 24, 2022

This tutorial covers commonly encountered issues when upgrading a Concrete CMS theme from version 8 to version 9

Transferring ownership of an add-on and a theme
Nov 15, 2022
By katzueno.

If you encounter a Concrete CMS add-on or theme that you love but not being maintained, you may want to ask the author to help or take over the add-on or theme. Here is the quick step-by-step guide of how to transfer the ownership.

Was this information useful?
Thank you for your feedback.