Reputation: 21
I'm working with vuejs and want to create a clickable button which declared in data section. How can I do that?
<template>
{{my_btn}}
</template>
<script>
export default {
data() {
return {
my_btn: '<button class="btn btn-indigo outline" @click="sayhello">VISIT OUR WEBSITE</button>'
}
},
methods: {
sayhello(){
alert('hello');
}
}
}
</script>
Upvotes: 1
Views: 5658
Reputation: 521
This is how to create a button inside the data
method
but to display it as an HTML not string you'll need to add it inside the v-html attribute.
Note: that the contents are inserted as plain HTML - they will not be compiled as Vue templates, so you should add event listener inside mounted
Lifecycle.
note: I add id
to your text so i'll be able to get the element and add an event listener
<template>
<div>
<span v-html="my_btn"></span>
</div>
</template>
<script>
export default {
data() {
return {
my_btn:
'<button id="btn" class="btn btn-indigo outline">VISIT OUR WEBSITE </button>'
};
},
methods: {
sayhello() {
alert("hello");
}
},
mounted() {
document.getElementById("btn").addEventListener("click", this.sayhello)
}
};
</script>
in the end, you can do it with the vue
way to avoid the risk of rendering arbitrary HTML on your website because it can be very dangerous it can easily lead to XSS attacks
.
<template>
<div>
<button class="btn btn-indigo outline" @click="sayhello">VISIT OUR WEBSITE
</button>
</div>
</template>
<script>
export default {
data() {
return {
}
},
methods: {
sayhello(){
alert('hello');
}
}
}
</script>
I hope you find it usfull
Upvotes: 3