1

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>
1

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, this was helpful

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.