Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Generic component to select all checkboxes
//+ Jonas Raoni Soares Silva
//@ http://raoni.org
<template lang="pug">
span.field(@click.stop="")
input.is-checkradio(
v-bind="$attrs"
type="checkbox"
ref="checkbox"
:indeterminate.prop="status === null"
:checked="status === true"
:id="id"
@click="select"
)
label(:for="id" :class="{'empty-label': hasEmptyLabel}") {{label}}
</template>
<script>
export default {
inheritAttrs: false,
name: 'select-all-checkbox',
props: {
status: {
Boolean,
default: null
},
selector: {
type: [String, Function],
required: true
},
label: {
type: String
},
id: {
type: String,
default: () => 'select-all-' + Math.random().toString(36)
},
validationMessage: String
},
computed: {
hasEmptyLabel () {
return this.label === undefined || !this.label.length;
}
},
mounted () {
this.updateValidationMessage();
},
watch: {
validationMessage () {
this.updateValidationMessage();
}
},
methods: {
updateValidationMessage () {
this.$refs.checkbox.setCustomValidity(this.validationMessage);
if (!this.validationMessage) {
this.$refs.checkbox.blur();
}
},
getList () {
return this.selector instanceof Function
? this.selector(this.$el)
: document.body.querySelectorAll(this.selector);
},
select (event) {
const checkbox = this.$refs.checkbox;
for (const item of this.getList()) {
if (item.checked !== checkbox.checked) {
item.click();
}
}
this.$emit('input', checkbox.checked);
}
}
};
</script>
<style lang="scss" scoped>
[type='checkbox'].is-checkradio + label.empty-label {
padding-left: 1rem;
}
</style>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment