我已经忙了很长时间了,还没有想出解决方案。问题是,我希望使用 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 应用程序中进行选择,让同一页面上的另一个应用程序知道它并接收所选数据以进一步处理它
最佳答案
您可以尝试使用 window.name
将根 Vue 节点存储为全局变量
define(["./app2/app"], function (CustomerSelectApp) {
window.VueRoot = CustomerSelectApp.init("#app");
});
然后在你的应用程序的其他部分你可以拥有
VueRoot.method();
VueRoot.data = value;
VueRoot.$emit('event', data);
我建议只对您的根节点执行此操作,否则会污染您的全局命名空间。
关于javascript - 从 Vue 应用程序外部访问 Vue 方法或事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38199665/