vue拼接html中onclick的触发方式,模版字符串拼接点击事件在vue项目中不生效问题
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;
}
魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐


所有评论(0)