Vue v-on:click does not work on component

ghz 8months ago ⋅ 88 views

I'm trying to use the on click directive inside a component but it does not seem to work. When I click the component nothings happens when I should get a 'test clicked' in the console. I don't see any errors in the console, so I don't know what am I doing wrong.

index.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>vuetest</title>
  </head>
  <body>
    <div id="app"></div>
    <!-- built files will be auto injected -->
  </body>
</html>

App.vue

<template>
  <div id="app">
    <test v-on:click="testFunction"></test>
  </div>
</template>

<script>
import Test from './components/Test'

export default {
  name: 'app',
  methods: {
    testFunction: function (event) {
      console.log('test clicked')
    }
  },
  components: {
    Test
  }
}
</script>

Test.vue (the component)

<template>
  <div>
    click here
  </div>
</template>

<script>
export default {
  name: 'test',
  data () {
    return {
      msg: 'Welcome to Your Vue.js App'
    }
  }
}
</script>

Answers

The v-on:click directive is meant to be used on HTML elements like <button> or <div> to capture click events. However, in your example, you are trying to use it on a custom component <test>, which won't work as expected.

To achieve the desired behavior, you need to forward the click event from the <test> component to the parent component (in this case, App.vue) where you handle it. You can achieve this by emitting a custom event from the <test> component when it's clicked, and then listen for this event in the parent component.

Here's how you can modify your code to make it work:

App.vue:

<template>
  <div id="app">
    <test @click="testFunction"></test>
  </div>
</template>

<script>
import Test from './components/Test'

export default {
  name: 'app',
  methods: {
    testFunction: function () {
      console.log('test clicked')
    }
  },
  components: {
    Test
  }
}
</script>

Test.vue:

<template>
  <div @click="$emit('click')">
    click here
  </div>
</template>

<script>
export default {
  name: 'test'
}
</script>

In this modified code:

  • In App.vue, we're now listening for a custom event @click emitted by the <test> component.
  • In Test.vue, we've added a click event listener on the <div> element and emitted a custom event click when the <div> is clicked.

This way, when you click on the <div> inside the <test> component, it will emit a click event, which will be captured by the parent component App.vue, and the testFunction method will be called.