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>'
}
})
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.
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.
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With