TheWebs
TheWebs

Reputation: 12923

How am I suppose to get the value of a checkbox?

So I have the following element:

<input v-on:click="$emit('addPartId', $event)" v-bind:value="13209" name="add_13209" type="checkbox">

Which then calls the following method:

 methods: {
        ....

        addPartId(evnt) {
            console.log(evnt);
        }
    },

In the parent container and is passed to the child:

    <table-body
        v-bind:items="items"
        v-bind:columns="columns"
        v-bind:sort-column="sortColumn"
        v-bind:direction="direction"
        @sort="sort"
        @addPartId="addPartId"
        >
    </table-body>

The question I have, that I can't find on stack, is how do I register a click event so that when the checkbox is clicked I get the event object (I want the value, from v-bind:value, of the checkbox.

Upvotes: 0

Views: 136

Answers (1)

Sphinx
Sphinx

Reputation: 10729

You should use event name which is the kebab-cased version, check Vue Guide: Custom Event,

As the guide says:

Unlike components and props, event names will never be used as variable or property names in JavaScript, so there’s no reason to use camelCase or PascalCase. Additionally, v-on event listeners inside DOM templates will be automatically transformed to lowercase (due to HTML’s case-insensitivity), so v-on:myEvent would become v-on:myevent – making myEvent impossible to listen to.

For these reasons, we recommend you always use kebab-case for event names.

Vue.component('my-checkbox', {
  template: `
    <input v-on:click="$emit('add-part-id', {'whole': $event, 'value':13209})" v-bind:value="13209" name="add_13209" type="checkbox">
  `
})

Vue.component('my-another-checkbox', {
  template: `
    <input v-on:click="$emit('add-part-id', $event)" v-bind:value="13209" name="add_13209" type="checkbox">
  `
})

new Vue({
  el: '#emit-example-simple',
  methods: {
    getChecked1: function (ev) {
      console.log('checkbox1', ev.value)
      console.log('checkbox1', ev.whole.target.value)
    },
    getChecked2: function (ev) {
      console.log('checkbox2', ev.target.value)
    }
  }
})
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<div id="emit-example-simple">
  First Example: <my-checkbox @add-part-id="getChecked1"></my-checkbox>
  Second Example: <my-another-checkbox @add-part-id="getChecked2"></my-another-checkbox>
</div>

Upvotes: 1

Related Questions