Vue通过js代码调用vue实例,解决v-html字符串里存在点击事件无效的问题

方法适用Vue.js和Vue-cli

先来说一下我的应用场景, 使用leaflet地图时, 点击地图的标注点弹出一个信息框, 里面有个按钮, 这时问题就来了, 这个api是需要传一段html进去的, 里面包含调用vue实例的方法

res.data.forEach(item => {
    this.markerPoint(item.locs[0].lat, item.locs[0].lng, carMakerIcon,
    `
        <h2 style="text-align: center;">车辆信息</h2>
        <div><b>车牌号码</b>:${item.locs[0].name}</div>
        <div><b>分组名称</b>:${item.locs[0].dept}</div>
        <div><b>位置时间</b>:${item.locs[0].gpstime}</div>
        <div><b>所在位置</b>:${item.locs[0].info}</div>
        <div><b>方向</b>:${item.locs[0].direct}</div>
        <div><b>状态</b>:${item.locs[0].state}</div>
        <div><b>行驶里程</b>:${item.locs[0].distance} km</div>
        <div><b>行驶总里程</b>:${item.locs[0].totalDis} km</div>
        <div style="margin-top: 10px;text-align: right">
        <button @click="getVehiclesHisData('${item.vid}','${item.vKey}')">运动轨迹</button></div>
	`);
})

可以看到最后一行, 我使用了@click, 但是vue不会编译html字符串的, 导致点击事件无效, 所以只能另寻办法

如果是只有一个点的情况下就好解决, 但是现在我是多个点要动态生成

于是找到一种目前能完美解决方法, 但不太规范

在初始化页面时将vue的实例对象赋值到全局变量中

<script>
export default {
  data() {
    return {
    }
  },
  mounted() {
      //this是当前vue实例对象
      window.mapVue = this;
  }
}
</script>

然后我html的的字符串中不再使用@click, 这时候使用onclick原生的方式调用js
res.data.forEach(item => {
    this.markerPoint(item.locs[0].lat, item.locs[0].lng, carMakerIcon,
    `
        <h2 style="text-align: center;">车辆信息</h2>
        <div><b>车牌号码</b>:${item.locs[0].name}</div>
        <div><b>分组名称</b>:${item.locs[0].dept}</div>
        <div><b>位置时间</b>:${item.locs[0].gpstime}</div>
        <div><b>所在位置</b>:${item.locs[0].info}</div>
        <div><b>方向</b>:${item.locs[0].direct}</div>
        <div><b>状态</b>:${item.locs[0].state}</div>
        <div><b>行驶里程</b>:${item.locs[0].distance} km</div>
        <div><b>行驶总里程</b>:${item.locs[0].totalDis} km</div>
        <div style="margin-top: 10px;text-align: right">
        <button οnclick="getVehiclesHisData('${item.vid}','${item.vKey}')">运动轨迹</button></div>
	`);
})

在vue实例外声明一个js 方法, 然后再调用vue里面的东西, window.mapVue 就相当于平时vue里面this那样正常使用, 外部的js只是起到一个代理作用
<script>
export default {
    data() {
        return {
        }
    },
    mounted() {
        //this是当前vue实例对象
        window.mapVue = this;
    },
    methods:{
        getVehiclesHisData(vid, vKey){
            console.info(`vue => ${vid}, ${vKey}`)
        }
    }
}

window.getVehiclesHisData = function (vid, vKey){
  console.info(`js => ${vid}, ${vKey}`)
  //通过全局调用vue实例对象
  window.mapVue.getVehiclesHisData(vid, vKey);
}
</script>

终极写法 : 甚至懒一点连js都被不用写了, 直接调用全局Vue实例
<button onclick="window.mapVue.getVehiclesHisData('${item.vid}','${item.vKey}')">运动轨迹</button>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值