简体   繁体   中英

Handling checkboxes in VueJS

I have been working with jQuery in past now I switched to Vuejs . I am unable to find a solution to these problems in Vuejs , I am newbie to vuejs .

  1. I had a range of checkboxes in a table. and I have added a snippet to select multiple checkboxes with shift + click . This way I was able to select many checkboxes at once..

     $chkboxes = $('.chkbox') lastChecked = null $chkboxes.click (e) -> if !lastChecked lastChecked = this return if e.shiftKey start = $chkboxes.index(this) end = $chkboxes.index(lastChecked) $chkboxes.slice(Math.min(start, end), Math.max(start, end) + 1).prop 'checked', lastChecked.checked lastChecked = this return 
  2. on Click I can get the values from checkbox which I have added as data attrs

     $("#cameras_datatables tbody input[type='checkbox']:checked").each (index, control) -> camera_id = $(control).attr("data-val-id") api_id = $(control).attr("data-val-api-id") api_key = $(control).attr("data-val-api_key") row = $(this).parents('tr') 

Now I have a button such as

<button v-on:click="onModifyClick" class="clear-btn-f" id="btn-modify">Modify</button>

and in methods

  onModifyClick () {
    console.log("testing");
    this.$notify({
      group: "admins",
      title: "Please",
      type: "error",
      text: "At least select one user!",
    });
  }

on Modify Click I want to get all those checkboxes which are checked on page.. and then I want to get the values which I have been added as attrs

<input type="checkbox" data-val="11172" data-val-username="junaid@evercam.io" data-val-api-id="dddd" data-val-api_key="dddd">

I want to loop through all checked checkboxes and get those data attrs,

This is more like an Informatory question because I have searched but cannot find any solutions about this.

UPDATE:

I am using Vuetable, And I am getting all those values through Vuetable loading in a callback formatter

export default [
  {
    title: ``,
    formatter: (value) => {
      return "<input type='checkbox' data-val='" + value.id + "' data-val-username='" + value.username +  "' data-val-api-id='" + value.api_id + "' data-val-api_key='" + value.api_key + "'>";
    },
    titleClass: "user-checkbox"
  }
]

Now, I see no way. to do what you are suggesting putting that into data and let Vue attach it to dom through the template. whereas the data is already getting bind to Dom through Vuetable.

After that I only have this

在此处输入图片说明

As is very common for new SPA framework users, you're doing this exactly backwards. You'll need to get out of the habit of touching the DOM directly when using Vue -- instead of thinking in terms of "I have these checkboxes, I need to read the values from them" it should be "I have these state variables in my component, and vue will automatically reflect those values inside the DOM." Manipulate the component data and let Vue worry about the DOM.

So, for example, instead of using jQuery to search the DOM for checkbox elements and read from / write to their attributes, use Vue to store those values and let its template draw them into the DOM, as in this simplified example:

 new Vue({ el: '#app', data: { myCheckboxes: [{ val: 11172, username: 'junaid@evercam.io', apiId: 'dddd', apiKey: 'xxxx', checked: false }, { val: 123, username: 'foo@example.com', apiId: 'dddd', apiKey: 'xxxx', checked: true }, { val: 456, username: 'bar@example.com', apiId: 'dddd', apiKey: 'xxxx', checked: true } ] }, methods: { onModifyClick() { // Examine the data, not the DOM: var ret = this.myCheckboxes.map(x => { if (x.checked) return x.val }).filter(x => {return x}) console.log("Values of checked items: ", ret) } } }); 
 <script src="https://unpkg.com/vue@latest/dist/vue.min.js"></script> <div id="app"> <template v-for="box in myCheckboxes"> <input @change="onModifyClick()" type="checkbox" v-model="box.checked" :data-val="box.val" :data-val-username="box.username" :data-val-api-id="box.apiId" :data-val-api_key="box.apiKey"> {{box.username}}<br> </template> </div> 

As you can see, most of what you were trying to do manually with jQuery now happens automatically -- at any time you can just check the contents of the component's data to see the state of the "myCheckboxes" list, you never read anything from the DOM, and you never write to the DOM directly, just change the contents of the data and let Vue handle the rest.

In frameworks like Vue, React, or Angular, the DOM is a side effect, not the source of truth as you're used to in jQuery code. I'd strongly recommend not using jQuery alongside Vue, at least until you understand the framework well enough to know when it's safe and necessary to do so (not often).

You could take advantage of getAttribute element function, which return the value of the attribute passed as parameter, so we add method handler of change event which takes the event as parameter and we could access target property that represents the current element (check box input) by calling the getAttribute method as follows:

 new Vue({ el: '#app', data: { }, methods: { onModifyClick(e) { let t=e.target; console.log(t.getAttribute('data-val')); console.log(t.getAttribute('data-val-username')); console.log(t.getAttribute('data-val-api-id')); console.log(t.getAttribute('data-val-api_key')); } } }); 
 <script src="https://unpkg.com/vue@latest/dist/vue.min.js"></script> <div id="app"> <input type="checkbox" data-val="11172" data-val-username="junaid@evercam.io" data-val-api-id="dddd" data-val-api_key="dddd" @change="onModifyClick" /> 1 <input type="checkbox" data-val="54545" data-val-username="brahim@evercam.io" data-val-api-id="eee" data-val-api_key="fdsdf" @change="onModifyClick" /> 2 </div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM