How to define Vue 2 component that contains a checkbox?

Viewed 28

I've tried this about four times, and consistently find myself stuck.

Binding directly to a checkbox seems well documented. https://vuejs.org/guide/essentials/forms.html#checkbox shows

<input type="checkbox" id="checkbox" v-model="checked" />
<label for="checkbox">{{ checked }}</label>

But wrapping that up in a custom component, and then connecting to the component seems like something I can't get right.

I have another reference (which I can't find right now, but will update this question when I do) that has guided me toward the following solution:

<template>
  <div>
    <input type="checkbox" :name="prefix" :id="id" v-model="zheck"
      @change="$emit('checked', $event.target.checked)">
    <label :for="id"><span v-i18n>{{title}}</span></label>
  </div>
</template>

...

export default Vue.extend({
  name: 'LabelInput',
  props: {
    value: {
      type: Boolean,
    },
    title: {
      type: String,
      required: false,
      default: '',
    },
    prefix: {
      type: String,
      required: true,
    },
  },
  data() {
    return {
      zheck: this.value,
    };
  },

And its use: <label-input title="..." prefix="..." v-model="xyz"></label-input>

While label-input emits eventsxyz never seems to be updated.

What am I doing wrong?

0 Answers
Related