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 = this.imgUrl
        // console.log()
        const newWin = window.open(this.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;
}

猜你喜欢

转载自blog.csdn.net/Maxueyingying/article/details/131640265
今日推荐