10

我已经忙了很长时间了,还没有想出一个解决方案。问题是,我希望使用 Require JS 和 Vue/Vuex 构建的模块能够与外界通信。

我不想用这个

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

或jQuery

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

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

这是我的自定义元素

<div id="app">

    <customer-select></customer-select>

</div>

和我的 main.js。我正在使用 requirejs 加载我的 AMD 模块

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

我的 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
            }

        });
    }

};

});

有没有办法让应用程序/组件通过我传入的事件或引用与外界通信?

具体来说。我想在我的 Vue 应用程序中进行选择,并让同一页面上的另一个应用程序知道它并接收所选数据以进一步处理它

4

1 回答 1

6

您可以尝试使用将根 Vue 节点存储为全局变量window.name

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

然后在您的应用程序的其他部分中,您可以拥有

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

我建议只对您的根节点执行此操作,否则会污染您的全局命名空间。

于 2016-10-06T16:50:16.937 回答