将click事件绑定到动态插入的内容

将click事件绑定到动态插入的内容

本文介绍了Vue:将click事件绑定到动态插入的内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Vue应用程序,该应用程序从包含一些代码块的API请求一些html,例如< div class ="play-video"> ...</div>

I have a Vue app which requests some html from an API that contains some blocks like <div class="play-video">...</div>

通过axios用axios调用API,将其插入到dom中,如下所示:

Calling the API with axios via a promise, it is inserted into the dom something like:

< div v-if ="content" v-html ="content"></div>

如何通过 .play-video 类将点击事件绑定到子级?只是看着 content 更改,然后运行vanilla js查询选择器绑定到它们吗?

How can I bind click events to the children with the .play-video class? Is it just a matter of watching for content to change, and then running vanilla js query selectors to bind to them?

推荐答案

通过添加 @click 处理程序并使用 Element.matches()

You can use some event delegation by adding a @click handler and checking the target element using Element.matches()

new Vue({
  el: '#app',
  data: {
    content: null
  },
  methods: {
    handleClick(e) {
      if (e.target.matches('.play-video, .play-video *')) {
        console.log('Got a click on .play-video or a child element')
      }
    }
  },
  mounted () {
    // simulate loading content
    setTimeout(() => {
      this.content = `
        <div>
          <p>Some other element</p>
          <button>I'm not part of <code>.play-video</code></button>
          <div class="play-video">
            <p><button>Click me, I am!</button></p>
          </div>
        </div>
        `
    }, 1000)
  }
})
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.min.js"></script>
<div id="app">
  <div v-if="content" v-html="content" @click="handleClick"></div>
  <p v-else>Loading...</p>
</div>

如果您只想捕获 .play-video 元素本身而不是其任何子元素上的点击事件,请将选择器更改为'.play-video'.

If you only want to catch click events on the .play-video element itself and not any of its children, change the selector to just '.play-video'.

请参见 https://developer.mozilla.org/en-US/docs/Web/API/Element/matches#Polyfill 以实现浏览器兼容性,并在需要时使用polyfill.

See https://developer.mozilla.org/en-US/docs/Web/API/Element/matches#Polyfill for browser compatibility and a polyfill if required.

这篇关于Vue:将click事件绑定到动态插入的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 16:02