ホーム > Vue > How to Get Event of Button Click in Vue
Vue

How to Get Event of Button Click in Vue

Thank you for your continued support.
This article contains advertisements that help fund our operations.

Summary of how to get the event of a button click in Vue

⇨ Click here for the table of contents for Vue articles

How to Get Event of Button Click in Vue

Simply put, starting with the conclusion

<template>
  <div><button @click="test">Test</button></div>
</template>

<script>
  export default {
    methods: {
      test(e) {
        console.log(e)
      },
    },
  }
</script>

By writing like this, you can get the event.

Failed Example

@click="test()"

Writing like this will result in failure.

How to use the event?

Want to get the text of the button

<script>
  export default {
    methods: {
      test(e) {
        console.log(e.target.value)
      },
    },
  }
</script>

Want to freely do various things with data attributes on the button

<template>
  <div>
    <button @click="test" data-korehatest="This is a test">Test</button>
  </div>
</template>

<script>
  export default {
    methods: {
      test(e) {
        console.log(e.target.dataset.korehatest)
      },
    },
  }
</script>

With data attributes, you can store various data freely.

When you want to use variables in data attributes, use v-bind

<template>
  <div>
    <button @click="test" :data-korehatest="text">Test</button>
  </div>
</template>

<script>
  export default {
    data() {
      return {
        text: "This is a test",
      }
    },
    methods: {
      test(e) {
        console.log(e.target.dataset.korehatest)
      },
    },
  }
</script>

Summary

That's all.

I hope it can be useful for someone.

This blog is supported by ad clicks. Thank you.

Until next time!

Please Provide Feedback
We would appreciate your feedback on this article. Feel free to leave a comment on any relevant YouTube video or reach out through the contact form. Thank you!