Home PHPMagento Declaratively Initialize JavaScript Component (x-magento-init)

Declaratively Initialize JavaScript Component (x-magento-init)

by Nima Riahi
app/code/Arkad/JsFun/view/frontend/templates/vue-test.phtml
<div id="vue-test">
    <h1>{{ message }}</h1>
</div>

<script type="text/x-magento-init"> 
/**
 * Target the DOM element with a standard JavaScrip selector. You may also
 * replace the selector with "*" to target all elements. The next property is
 * the JavaScript component you wish to initialize, with the value of an object
 * containing properties you wish to set for that component.
 */
{
    "#vue-test": {
        "Arkad_JsFun/js/vue-test": {
            "message": "Declarative test"
        }
    }
}
</script>
app/code/Arkad/JsFun/view/frontend/web/js/vue-test.js
/**
 * If you use "*" to target all elements, the element property within the
 * callback will be null because RequireJS won't know which specific element you
 * wish to refeference. In this case, hardcode a selector or use an HTML class
 * attribute rather than an ID selector within your JS initialization.
 */
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