How to bind a click event on “v-html” in Vue

删除回忆录丶 提交于 2019-12-21 01:18:38

问题


I have a simple example in jsfiddle, as described in the example, I want to insert the element via v-html and then bind the event in the insert element. In addition to adding id operation dom this way, is there a better way?

https://jsfiddle.net/limingyang/bnLmx1en/1/

<script src="https://unpkg.com/vue/dist/vue.js"></script>
<div id="app">
    <div v-html="link"></div>
</div>

var app = new Vue({
    el: '#app',
    data: {
        link: '<a href="javascript:void(0)">click me</a>'
    }
})

回答1:


You can add a ref on your div, and operate with its children elements like you do in regular JavaScript. For example, you can set an event listener for a link inside mounted hook:

var app = new Vue({
  el: '#app',
  data: {
    link: '<a href="#">click me</a>'
  },
  mounted() {
    this.$refs['mydiv'].firstChild.addEventListener('click', function(event) {
      event.preventDefault();
      console.log('clicked: ', event.target);
    })
  }
})
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<div id="app">
    <div v-html="link" ref="mydiv"></div> <!-- notice 'ref' -->
</div>


来源:https://stackoverflow.com/questions/44483117/how-to-bind-a-click-event-on-v-html-in-vue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!