字符串拼接 与 三目运算符,$nextTick

项目中在百度地图上绘制 信息窗口 的的时候需要获取后台数据进行绘制,可是用的时候用户并没有添加数据,

所以后台返回 字段 为 null,显示在页面中不太美观,然后就遇到了我要记录的问题:

地图绘制代码:

updated() { // 页面更新时调用
   this.$nextTick(() => {
     if (this.isReady) {
       this.initMap()
     }
   })
},

// 地图绘制
initMap() {
        /* eslint-disable */
    console.log('地图初始化monInfo' + JSON.stringify(this.monInfo))
    var map = new BMap.Map('allmap')
    var point = new BMap.Point(this.mapInit.lng, this.mapInit.lat)
    map.centerAndZoom(point, 15)
    var marker = new BMap.Marker(point) // 创建标注
    map.addOverlay(marker) // 将标注添加到地图中
    var top_left_navigation = new BMap.NavigationControl() // 左上角,添加默认缩放平移控件
    map.addControl(top_left_navigation)
    map.enableScrollWheelZoom(true)
    var opts = {                  // 定义信息窗口样式
      width: 200, // 信息窗口宽度
      height: 100, // 信息窗口高度
      enableMessage: true // 设置允许信息窗发送短息
    }
    var html = ''
    const json = JSON.parse(this.monInfo.realTimeData)
    html += '<div>车牌:' + this.monInfo.plateNo + '</div>'
    html += '<div>速度:' + json.CurrentSpeed + '</div>'
    html += '<div>时间:' + this.monInfo.alarmStart + '</div>'
    html += '<div>地址:' + this.monInfo.alarmAddress + '</div>'
    var infoWindow = new BMap.InfoWindow(html, opts)
    /* eslint-enable */
    setTimeout(function() {
      map.openInfoWindow(infoWindow, point) // 绘制信息窗口
    }, 600)
}

$nextTick会在DOM完成更新之后调用,可以说是总是在最后调用的,当前代码渲染完毕之后调用

// 举例

this.$nextTick(() => { // 清除表格checked勾选
  this.$refs.multipleTable.clearSelection()
})

this.$nextTick(() => { // 清除form表单效验
  this.$refs['addForm'].clearValidate()
})

// 在使用时需要考虑的就是$nextTick会在最后触发,DOM更新完毕,所有方法执行完毕之后。
// 只会应用$nextTick里的改变

有关于$nextTick 方法,详情请看这里

如果用户并没有设置地址,那么界面会是这个样子:

不太好看,所以需要做一下处理,详细如下:

var html = ''
const json = JSON.parse(this.monInfo.realTimeData)
html += '<div>车牌:' + this.monInfo.plateNo + '</div>'
html += '<div>速度:' + json.CurrentSpeed + '</div>'
html += '<div>时间:' + this.monInfo.alarmStart + '</div>'

// 单拿地址来说,如果这样写,没有问题,但是会显示null
html += '<div>地址:' + this.monInfo.alarmAddress + '</div>'

// 我尝试这这样写
html += '<div>地址:' + this.monInfo.alarmAddress === null ? '空' : 
this.monInfo.alarmAddress + '</div>'    // 还是不行

// 再这样
html += '<div>地址:' + this.monInfo.alarmAddress || '' + '</div>' // 也不行

// 正确的写法应该这样
const monInfoAlarmAddress = this.monInfo.alarmAddress === null ? '空' : this.monInfo.alarmAddress
html += '<div>地址:' + monInfoAlarmAddress  + '</div>'



var infoWindow = new BMap.InfoWindow(html, opts)
/* eslint-enable */


// 在页面绘制需要等待数据加载完成,所以600毫秒以后绘制
setTimeout(function() {
  map.openInfoWindow(infoWindow, point)
}, 600)

使用三目运算符直接拼接,界面是这样:

为什么使用三目拼接不行呐,可能原因是三目运算符先执行,然后里面执行结果有 return,所以这样写不行

而且我也试着用Vue的 computed 计算属性来做,也是不行,这里记录一下

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值