How to use the component as a button in vue.js?

by muriel.schmidt , in category: Javascript , 20 days ago

How to use the component as a button in vue.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by herminia_bruen , 19 days ago

@muriel.schmidt 

In Vue.js, you can use a component as a button by adding an event listener to the component and handling the click event. Here's an example of how you can do this:

  1. Define the component:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<template>
  <div @click="handleClick" class="button">Click me</div>
</template>

<script>
export default {
  methods: {
    handleClick() {
      console.log('Button clicked!');
      // Add your button click logic here
    }
  }
}
</script>

<style>
.button {
  background-color: blue;
  color: white;
  padding: 10px 20px;
  cursor: pointer;
}
</style>


  1. Import the component and use it as a button in your parent component:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
<template>
  <div>
    <ButtonComponent />
  </div>
</template>

<script>
import ButtonComponent from './ButtonComponent.vue';

export default {
  components: {
    ButtonComponent
  }
}
</script>


In this example, when you click on the ButtonComponent, the handleClick method will be triggered and the console log 'Button clicked!' will be displayed. You can replace this with your desired button click logic. The component is styled to look like a button, with a blue background color and white text.