Checkbox/Radio component implementation
-
Today I was thinking about some custom checkboxes I had to implement on a project, that alas does not use Quasar. At one point I looked at the checkbox component code from Quasar and I really liked the way you have implemented the
model
computed property, really clean. But as I read the docs,input:checkbox
can be assigned to an array when itsvalue
is set, this way it will add or remove its value from the array, something we cant really do without reinventing the wheel (check to see if the passedv-model
value is array, and if current value exists yada yada), so I tried instead of assigningthis.model = this.value
in theselect
method, simply to do athis.$refs.checkbox.click()
, its native and it actually works pretty good. Here is my implementation, maybe it could help someone else. If this is a bad idea, I would really like someone to tell me early on
Bellow is the radio implementation, checkbox is pretty much the same.<div class="input-styled radio"> <input class="input" type="radio" v-model="model" :value="value" :name="name" :disabled="disable" ref="radio" @click.stop > <label @click.stop.prevent="select"> <span class="styled-element"/> {{ title }} </label> </div>
export default { props: { value: { required: true // passed from the parent to populate the radio's Value }, checked: { required: true // passed by v-model to sync the :checked property }, disable: Boolean, title: { required: true }, name: { type: String, default: '' }, id: {} }, model: { // new property since 2.2 prop: 'checked', // set the parent's property thats passes to v-model to the checked prop on the child event: 'change' // do the above action when this event is fired }, computed: { model: { get () { return this.checked // just return the value from v-model }, set (value) { if (value !== this.checked) { this.$emit('change', value) // when we set this.model we emit an event with the current value } } }, _id () { return this.id ? this.id : this._uid + '_' + this.checked } }, methods: { select () { this.$refs.radio.click() // trigger a click on the input element } } }