网页与UE通信基础搭建
1.引入基本的js脚本
在index.html中引入js脚本,代码如下 :
"object" != typeof ue || "object" != typeof ue.interface
? ("object" != typeof ue && (ue = {}),
(ue.interface = {}),
(ue.interface.broadcast = function (e, t) {
if ("string" == typeof e) {
var o = [e, ""];
void 0 !== t && (o[1] = t);
var n = encodeURIComponent(JSON.stringify(o));
"object" == typeof history && "function" == typeof history.pushState
? (history.pushState({}, "", "#" + n),
history.pushState({}, "", "#" + encodeURIComponent("[]")))
: ((document.location.hash = n),
(document.location.hash = encodeURIComponent("[]")));
}
}))
: (function (e) {
(ue.interface = {}),
(ue.interface.broadcast = function (t, o) {
"string" == typeof t &&
(void 0 !== o
? e.broadcast(t, JSON.stringify(o))
: e.broadcast(t, ""));
});
})(ue.interface),
(ue5 = ue.interface.broadcast);
ue.interface.emitUE = function (params) {
if (!_bus) return;
console.log("emitUE", params);
if (typeof params === "string") params = JSON.parse(params);
const { type, data } = params;
// 页面跳转 // {type:'redirect_webpage',data:{url:'/path/to/page'}}
// 关闭legend // {type: 'legend_change', data: {text:'全域视角', is_select:0}}
_bus.emit(type, data);
};
window.sendToUE = (data) => ue5("toUE", data);
2.定义一个META文件,记录网页全局的一些参数
代码如下:
import { ref } from "vue";
import mitt from "mitt";
const meta = {
current_path: ref("/"),
mode: ref(""),
};
window._meta = meta;
window._bus = meta.bus = mitt();
window.META = meta;
export default meta;
3.在router.js的路由守卫中及时修改全局的参数
代码如下:
import META from "@/META.js";
...
const router = createRouter({
routes,
history: createWebHashHistory(),
});
router.beforeEach((to, from) => {
META.current_path.value = to.path;
META.mode.value = to.meta.name || "default";
});
4.定义一个函数,约定一个发送给UE的数据的格式
代码如下:
import META from "@/META.js";
// 发送数据到UE的方法 // 该方法会自动添加 mode / page
window.sendToUE5 = (data) => {
const params = {
...data,
page: META.current_path.value,
mode: META.mode.value,
}
console.log("sendToUE", params)
sendToUE(params);
};
5.函数使用
const params = {
type: "bnt-click",
page: META.current_path.value,
data: {
text: '场景切换',
is_selected: is_selected ? 1 : 0,
},
};
sendToUE5(params);