Vue.js 2 v2.Vuetify get Value from checkboxes using bitwise AND

58 Views Asked by At

I have info about active modules stored in an int rather than in an array and use bitwise AND to show the active ones:

<p>Privileges: {{ privileges }}</p>
<v-checkbox 
  v-for="(b,bi) in allModules.sort((x,y) => x.privileges - y.privileges)"
  :label="b.name"
  :input-value="(b.privileges & privileges)!=0"
 >
 </v-checkbox>

Not sure if it is the best way to manage, but for showing the data.. it works

Now, I would like to "read" the value of the checked checkboxes: for example, if I check only the first 3 checkboxes having respectively b.privileges of 2,4 and 8 I would like to read in this.privileges the value of 14 (or even the array [2,4,8] that I can easily summarize)

how can achieve it?

I've prepared a working example on codepen

Thanks!

1

There are 1 best solutions below

1
Moritz Ringler On BEST ANSWER

You can use the @change event to update the privileges value when a checkbox is clicked:

<v-checkbox 
  v-for="(b,bi) in allModules"
  :input-value="(b.privileges & privileges) != 0"
  @change="isSet => updatePrivileges(b.privileges, isSet)"
  ...
/>

If the privilege is added, do a boolean or operation. To remove it, you can do and with the negation of the privilege (keep bits not set in the privilege):

updatePrivileges(privilegeBit, isSet){
  this.privileges = isSet 
    ? (this.privileges | privilegeBit) 
    : (this.privileges & ~privilegeBit)
}

(~ is bitwise not)

Here is the updated codepen