vue拼接html中onclick的触发方式,模版字符串拼接点击事件在vue项目中不生效问题

模版字符串拼接点击事件在vue项目中不生效问题

下面的点击事件没有任何效果,但是如果换成onclick绑定事件则会提示没有该方法。主要原因是:

模版字符串中拼接的html片段中的方法调不到vue中this.methods里的东西,因为methods里的代码是编译后在浏览器里运行的,这个时候拼接的方法绑定的click 被当成字符串解析了。

代码
在这里插入图片描述
但是问题来了,模版字符串中onclick的点击事件,无法调用vue的methods中的方法,需要按照原生方式来写,所以就需要将goClick方法绑定到全局对象window

正确写法

  mounted() {
    //模板参数传参
    let _this = this;
    window.getClick = _this.getClick;
  },
  methods: {
    getClick:function (imgUrl) {
      if (imgUrl) {
        const img = new Image()
        img.src =imgUrl
        // console.log()
        const newWin = window.open(imgUrl, '_blank')
        newWin.document.write(img.outerHTML)
        newWin.document.body.style.background = '#000';
        newWin.document.body.style.marginLeft = '0px';
        newWin.document.body.style.height = '100%';
        newWin.document.body.style.marginTop = '20px';
        newWin.document.body.style.marginRight = '0px';
        newWin.document.body.style.marginBottom = '0px';
        newWin.document.body.style.textAlign = 'center';
        newWin.document.close()
      } else {
     }
  }

步骤

1.首先你有一段拼接的html代码

let conten=`<button οnclick="come()">点我</button>`;

2.然后你需要在methods中有一个函数

methods:{
	come:function(){
		alert('你好,再见!')
	},
}

3.下一步就是连接起桥梁的关键点

created(){
	let _this=this;
	window.come=_this.come;
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值