How to call methods of a VueJS app from outside

While working on my VueJs product configurator I faced the challenge to call functions in a VueJs app from „outside“, meaning the VueJs app is e.g. integrated into a PHP shopping application like Oxid eShop, Shopware or Magento and I have to e.g. check the state of the current configuration inside the VueJs app.

In particular, I had to check if the configuration is finished when the „to basket“ button on the detail page of the shop is clicked and of course get the configured product back from the app to add it to the basket.

One way I’ve found to achieve this it to save the VueJs instance into a global window variable like this:

window.confApp = new Vue({
    el:’#configurator‘,
    render(h) {
        return h(App, {
            props: {
                apiUrl:this.$el.attributes.apiUrl.value
            }
        })
    }
})

 

This way, you can access it from anywhere on the page and add a script to a Smarty template of the shop e.g.:

$(function() {
    $(‚#toBasket‘).on(‚click‘, function(e) {
        console.log(window.confApp);
        return true;
    }
});

 

Now, to find the Vue Component inside the Vue object you can inspect the object in the browser console, it is probably nested in the „$children“ array of the Vue instance:

You can see the functions of the Component in the screenshot, the one we need is the „exportConfiguration“ which can now be called like this:

$(function() {
    $(‚#toBasket‘).on(‚click‘, function(e) {
        // get global configurator VUE instance

        var configurator = window.confApp.$children[0];
        var configuration = configurator.exportConfiguration();
        if (!configuration) {
            return false;
        }
        return true;
     }
});

 

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert.