Last active
April 10, 2020 18:30
-
-
Save jonasraoni/54b7b9c213e982cb6323a4edb2c91228 to your computer and use it in GitHub Desktop.
Generic component to select all checkboxes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//+ 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