Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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>'
    }
})
like image 840
李明洋 Avatar asked Jun 11 '17 11:06

李明洋


People also ask

How do you link Vue and HTML?

The simplest way to get started with Vue is to grab the development version script for it and add it to the head tag of your HTML file. Then you can start Vue code inside the HTML file inside of script tags. And have the Vue code connect up with an existing element on your HTML page.

What is V-bind in Vue?

The v-bind directive is a Vuejs directive used to bind one or more attributes, or a component prop to an element. If that attribute is binded to our data defined in Vuejs instance then dynamically changes can be observed as data changes.

What is V HTML in Vue JS?

The v-html directive is a Vue. js directive used to update a element's inner HTML with our data. This is what separates it from v-text which means while v-text accepts string and treats it as a string it will accept string and render it into HTML.


1 Answers

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>
like image 186
Egor Stambakio Avatar answered Sep 21 '22 20:09

Egor Stambakio