0

I have a component with checkbox input:

<template>
    <input id='one' type='checkbox' v-on:change.native="$emit('change')" />
</template>

I am using this component in another component:

<template>
....
    <Checkbox v-on:change="change" />
....
</template>
<script>
    import Checkbox from './components/Checkbox.vue'

    export default {
        components: {
            Checkbox
        },
        methods: {
            change: function (e) { 
                console.log(e);
        },
    }
</script>

What I want is to attach parent component method, which must point to children component event. The problem is that this change event doesn't trigger when checkbox is changed.

2 Answers 2

2

You need to use the input event for checkboxes. I'd also recommend using v-on="$listeners" in the Checkbox component unless you really need to name the event 'change'.

Checkbox.vue

<template>
  <input
    type="checkbox"
    v-on="$listeners"
  >
</template>

index.vue

<template>
  <Checkbox @input="input" />
</template>

<script>
import Checkbox from '~/components/Checkbox.vue';

export default {
  components: {
    Checkbox,
  },
  methods: {
    input(e) {
      console.log(e);
    },
  },
};
</script>
Sign up to request clarification or add additional context in comments.

Comments

1

The .native modifier is used on components, not on native widgets.

There may be times when you want to listen directly to a native event on the root element of a component. In these cases, you can use the .native modifier for v-on

You could use .native in the outer binding to catch the change event bubbling from the inside (because native events generally bubble, while Vue events do not), or you could use non-.native events in both the inner and outer components to do your own bubbling.

The snippet below does both:

new Vue({
  el: '#app',
  methods: {
    change() {
      console.log("Native change");
    },
    change2() {
      console.log("Non-native");
    }
  },
  components: {
    myCheckbox: {
      template: '#inner-template'
    }
  }
});
<script src="https://unpkg.com/vue@latest/dist/vue.js"></script>
<template id="inner-template">
    <input id='one' type='checkbox' v-on:change="$emit('change')" />
</template>
<div id="app">
  <my-checkbox v-on:change.native="change" @change="change2"></my-checkbox>
</div>

Comments

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.