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

通过promise使用axios调用API,它被插入dom中,类似于:

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

如何将click事件绑定到.play-video类的子元素?是否只是观察content的变化,然后运行vanilla js查询 Select 器来绑定它们?

推荐答案

通过添加@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元素本身而不是其任何子元素上的单击事件,请将 Select 器更改为仅'.play-video'.

有关浏览器兼容性和polyfill(如果需要)的信息,请参见https://developer.mozilla.org/en-US/docs/Web/API/Element/matches#Polyfill.

Vue.js相关问答推荐

当props 的值改变时如何更新类'

元素不会对react 性props 的更改做出react

如何在 Vuetify 2 中的轮播项目上放置 href 属性?

在vuejs中使用表单追加时如何使用布尔值

JSDoc 单文件 Vue 组件

vue.js 在 App.vue 中获取路由名称

用 axios 搜索:新字符时取消之前的请求

在 jest document.querySelector 中测试 vue 组件期间始终返回 null

如何将对象作为props传递并让组件更新子对象

如何只查看数组中的一个对象?

为什么Vue.js 使用单字标签

Polyfill for ie

如何使用 vue-resource 添加额外的标头来发布请求?

Vue.js 如果在视图中

如何在 Vue 中转发 $refs

Vuetify v-btn 路由活动类问题

Vuejs 3 从子组件向父组件发出事件

异步方法不等待函数

偶数行格式化

根据nuxt中的url参数动态加载组件