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

时间:2018-12-20 23:27:29

标签: javascript vue.js

我有一个Vue应用程序,该应用程序从包含某些块(例如CIBlendWithMask

的API处请求一些html)

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

<div class="play-video">...</div>

如何将点击事件绑定到<div v-if="content" v-html="content"></div>类的孩子?只是看着.play-video进行更改,然后运行香草js查询选择器绑定到它们吗?

1 个答案:

答案 0 :(得分:6)

您可以通过添加@click处理程序并使用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/vue@2.5.21/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'

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

相关问题