Skip to content

Instantly share code, notes, and snippets.

@jonasraoni
Last active April 10, 2020 18:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jonasraoni/54b7b9c213e982cb6323a4edb2c91228 to your computer and use it in GitHub Desktop.
Save jonasraoni/54b7b9c213e982cb6323a4edb2c91228 to your computer and use it in GitHub Desktop.
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