在vue项目中,onclick事件如何调用vue的函数

写在前面

在 Vue 的项目中,通过拼接 html,插入到页面中的内容。html 中的 onclick 方法,如何触发 Vue 中的方法呢?

示例如下:

let info = []
info.push(`<span class='top-total'>10人</span><div class='list-wrapper'>`)
nearPersonArr.forEach(data => {
  info.push(
    `<span class='infowindow-span' οnclick='openPerson(${data.id})'>${data.name}</span><br/>`
  )
})
info.push('</div>')
document.body.appendChild(info)

我们把这个 info 插入到页面 dom 中。那么,这个 span 里面的 onclick 事件如何执行我们在 methods 中定义的方法呢?

methods: {
  openPerson(id) {
    console.log(id)
  }
}

解决办法

onclick 执行的是 window 环境中的方法,所以:将 this 中的方法关联到 window 上即可。

created() {
  window.openPerson = this.openPerson
}

-----------------(正文完)------------------

前端学习交流群,想进来面基的,可以加群: 685486827832485817
Vue学习交流 React学习交流

写在最后: 约定优于配置 —— 软件开发的简约原则

--------------------------------(完)--------------------------------------

我的:
个人网站: https://neveryu.github.io/neveryu/
Github: https://github.com/Neveryu
新浪微博: https://weibo.com/Neveryu
微信: miracle421354532

更多学习资源请关注我的新浪微博…好吗

Logo

前往低代码交流专区

更多推荐