Home PHPMagento Declaratively Initialize JavaScript Component (data-mage-init)

Declaratively Initialize JavaScript Component (data-mage-init)

by Nima Riahi
app/code/Arkad/JsFun/view/frontend/templates/vue-test.phtml
<!--
A special "data-mage-init" HTML attribute is declared on the main DOM element you wish to initialize,
and then the JavaScript component and properties are passed to it as a JSON string.
-->
<div id="vue-test"
     data-mage-init='{ "Arkad_JsFun/js/vue-test": { "message": "Another test" } }'>
    <h1>{{ message }}</h1>
</div>
app/code/Arkad/JsFun/view/frontend/web/js/vue-test.js
/**
 * The properties defined within the attribute are now accessible within the callback. For example,
 * the "message" property is now accessible as config.message.
 */
define(['vue'], function(Vue) {
    'use strict'

    return function(config, element) {
        return new Vue({
            el: '#' + element.id,
            data: {
                message: config.message
            }
        });
    };
});

You may also like

Leave a Comment