Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access Vue method or event from outside the Vue app

I've been busy with this for quite some time and haven't come up with a solution. The problem is, I want my module built with Require JS and Vue/Vuex to communicate with the outside world.

I don't want to use this

require(["myModule"],function(vm){
vm.$children[0].myMethod()
});

or jquery

// inside app
$(document).trigger("myEvent",payload);

// outside app
$(document).on("myEvent",myHandler);

This is my custom Element

<div id="app">

    <customer-select></customer-select>

</div>

and my main.js. I'm using requirejs to load my AMD modules

define(["./app2/app"], function (CustomerSelectApp) {
    CustomerSelectApp.init("#app");
});

my app.js

define([ "vue", "jquery", "webjars/nm-customer-select/nm-customer-select",
    "css!bootstrap-css" ],

function(Vue, $, customerSelect) {

return {
    init : function(targetElement) {
        return new Vue({
            el : targetElement,


            components : {
                customerSelect : customerSelect
            }

        });
    }

};

});

Is there any way to make the app/component communicate with the outside world via an event or a reference that I pass in?

Specifically. I want to make a selection in my Vue app and let another App on the same page know about it an receive the selected data to process it further

like image 737
Lord Habicht Avatar asked Jul 05 '16 09:07

Lord Habicht


1 Answers

You can try storing the root Vue node as a global variable using window.name

define(["./app2/app"], function (CustomerSelectApp) {
    window.VueRoot = CustomerSelectApp.init("#app");
});

Then in other parts of your application you can have

VueRoot.method();
VueRoot.data = value;
VueRoot.$emit('event', data);

I would suggest only doing this with your root node as it would pollute your global namespace otherwise.

like image 73
Justin MacArthur Avatar answered Oct 19 '22 07:10

Justin MacArthur