javascript-eval动态引入mqtt.min.js

在项目中一般mqtt是某一个特定的功能才会使用mqtt,而且mqtt体积也不小,所以一般是打开某些功能的时候才会进行mqtt加载,一般情况就是用fetch和eval配合一下。

fetch('/cdn/mqtt.min.js').then(res=> {
    res.text().then(t=> {
        let mqtt = eval(`${t};mqtt`)
        console.log(mqtt)
        const url = 'ws://127.0.0.1:8083/mqtt'
                const options = {
                    clean: true,
                    connectTimeout: 4000,
                    clientId: 'test',
                    username: 'test',
                    password: 'test',
                }
                const client = mqtt.connect(url, options)
                client.on('connect', function () {
                    client.subscribe('test', function (err) {
                        if (!err) {
                            client.publish('test', 'Hello mqtt')
                        }
                    })
                })

                client.on('message', function (topic, message) {
                    console.log(message.toString())
                })
    })
})

看了mqtt.Js的源码,因为它是直接var mqtt = .... 这样子的,在使用script标签加载的时候会产生一个全局变量mqtt,但是eval的时候不会产生这个全局的mqtt对象,所以需要拼接一下代码将里面声明的mqtt返回处理.

看看下面的代码就大概知道eval是怎么返回变量的了,eval会将最后一个语句块作为结果返回

let str = `var a = 1`;
let res = eval(str);
console.log(res)

//此时eval返回的var a = 1的结果, 所以输出的是undefined
//undefined


let str = `var a = 1;a`;
let res = eval(str);
console.log(res)
//此时eval返回的a的结果,因为a是最后的代码块, 所以输出的是1
//1

//分号; 是语句块结束的标记和换行是一样的
let str = `var a = 1
a`;
let res = eval(str);
console.log(res)
//此时eval返回的a的结果,因为a是最后的代码块, 所以输出的是1
//1

获取特勤线路详细信息失败 TypeError: _this6.$refs.mineMapRef.updateRealtimeRoute is not a function at _callee3$ (index.vue?./node_modules/babel-loader/lib/index.js!./node_modules/vue-loader/lib/index.js??vue-loader-options:701:39) at tryCatch (regeneratorRuntime.js:72:16) at Generator.eval (regeneratorRuntime.js:161:17) at Generator.eval [as next] (regeneratorRuntime.js:102:21) at asyncGeneratorStep (asyncToGenerator.js:9:24) at _next (asyncToGenerator.js:28:9)deviceArray: [__ob__: Observer] vue.js:4857 [Vue warn]: Error in v-on handler: "TypeError: Cannot read properties of undefined (reading 'realtime')" found in ---> <SpeLineList> at src/views/components/SpeLineDetail/index.vue <Index> at src/views/largeScreen/SpecialLine/index.vue <App> at src/views/App.vue <Root> warn$2 @ vue.js:4857 logError @ vue.js:3547 globalHandleError @ vue.js:3543 handleError @ vue.js:3511 invokeWithErrorHandling @ vue.js:3527 invoker @ vue.js:1461 invokeWithErrorHandling @ vue.js:3519 Vue.$emit @ vue.js:2638 _callee2$ @ index.vue?./node_modules/babel-loader/lib/index.js!./node_modules/vue-loader/lib/index.js??vue-loader-options:360 tryCatch @ regeneratorRuntime.js:72 eval @ regeneratorRuntime.js:161 eval @ regeneratorRuntime.js:102 asyncGeneratorStep @ asyncToGenerator.js:9 _next @ asyncToGenerator.js:28 Promise.then asyncGeneratorStep @ asyncToGenerator.js:18 _next @ asyncToGenerator.js:28 eval @ asyncToGenerator.js:33 Wrapper @ export.js:20 eval @ asyncToGenerator.js:25 submitForm @ index.vue?./node_modules/babel-loader/lib/index.js!./node_modules/vue-loader/lib/index.js??vue-loader-options:373 invokeWithErrorHandling @ vue.js:3519 invoker @ vue.js:1461 original_1._wrapper @ vue.js:7516 vue.js:3551 TypeError: Cannot read properties of undefined (reading 'realtime') at VueComponent.updateVehiclePosition (index.vue?./node_modules/babel-loader/lib/index.js!./node_modules/vue-loader/lib/index.js??vue-loader-options:475:19) at VueComponent.handlesHeadTq (index.vue?./node_modules/babel-loader/lib/index.js!./node_modules/vue-loader/lib/index.js??vue-loader-options:677:29) at VueComponent.handlestartTq (index.vue?./node_modules/babel-loader/lib/index.js!./node_modules/vue-loader/lib/index.js??vue-loader-options:668:12) at invokeWithErrorHandling (vue.js:3519:28) at VueComponent.invoker (vue.js:1461:16) at invokeWithErrorHandling (vue.js:3519:28) at Vue.$emit (vue.js:2638:11) at _callee2$ (index.vue?./node_modules/babel-loader/lib/index.js!./node_modules/vue-loader/lib/index.js??vue-loader-options:360:24) at tryCatch (regeneratorRuntime.js:72:16) at Generator.eval (regeneratorRuntime.js:161:17) 地图组件,父组件 // 特勤路线演习 handlestartTq(type) { this.deviceArray = [] console.log(this.deviceArray, 'aaaaaaaaaaaa'); console.log("type:", type, "deviceArray:", this.deviceArray); this.isStartTq=type this.handlesHeadTq() }, // 特勤路线演习-头车 handlesHeadTq() { console.log("deviceArray:", this.deviceArray); const dataPoints = this.deviceArray.map(item => ([ Number(item.longitude), Number(item.latitude) ])); this.$refs.mineMapRef.updateVehiclePosition(dataPoints[dataPoints.length - 1]) }, /** * @description:特勤线路详细信息 * @return {*} */ async handleTaskInfo(row) { try { const params = { id: row.id, }; const res = await getTqInfoApiBusiness(params); const dataPoints = res.data.xlData.map(item => ([ Number(item.longitude), Number(item.latitude) ])); this.$refs.mineMapRef.updateRealtimeRoute(dataPoints); this.$refs.mineMapRef.addRouteMarker(dataPoints[0], "end"); this.$refs.mineMapRef.addRouteMarker(dataPoints[dataPoints.length - 1], "start"); console.log(dataPoints, '获取特勤线路详细信息成功'); } catch (error) { console.log("获取特勤线路详细信息失败", error); } } //初始化MQTT initMQTT() { this.deviceArray = [] //开始链接MQTT const mqOptions = { clientId: new Date().getTime() + "", //客户端ID username: mqttUserName, //用户名 password: mqttUserPassword, //密码 keepalive: 30, //心跳时间 protocol: 'ws', //协议类型 reconnectPeriod: 30 * 1000, //两次重连间隔 connectTimeout: 40000, //重连超时时间 clean: true //设置为false,在离线时接收QoS 1和QoS 2消息 }; this.mqttClient = mqtt.connect(mqttAddress, mqOptions); // mqtt连接 this.mqttClient.on("connect", (e) => { this.mqttClient.subscribe('fusion-tqxl-gps', { qos: 0 }, (error) => { if (!error) { console.log('特勤路线【车载】订阅成功') } else { console.log('特勤路线【车载】订阅失败') } }) }); // 接收消息处理 this.mqttClient.on("message", (topic, message) => { const res = JSON.parse(message.toString()); // console.log("收到特勤路线【车载】00000", res) this.deviceArray.push(res) console.log("收到特勤路线【车载】", this.deviceArray) }); // 断开发起重连 this.mqttClient.on("reconnect", (error) => { console.log("特勤路线【车载】:", error); }); // 链接异常处理 this.mqttClient.on("error", (error) => { console.log("特勤路线【车载】:", error); }); },, watch: { deviceArray(newVal) { if (newVal.length > 0 && this.isStartTq) { this.handlesHeadTq(newVal) } }, },怎么修改报错,优化流程,在父组件获取到原路线先绘制 this.$refs.mineMapRef.updateRealtimeRoute(dataPoints); this.$refs.mineMapRef.addRouteMarker(dataPoints[0], "end"); this.$refs.mineMapRef.addRouteMarker(dataPoints[dataPoints.length - 1], "start");,在点击开始演习获取车辆实时位置handlestartTq,然后绘制新路线黄色,覆盖在原路线上,并且按照最新点位更新车辆图标
最新发布
07-26
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值