[Vuejs]-Precheck checkboxes depending on the response coming in json form in vuejs

0๐Ÿ‘

โœ…

I solved my problem, here is my code

role.component.js

    getRoleRowData(data) {
  this.roleaction = "edit";
  this.addrolemodal = true;
  console.log(data.role_id);
  let tempthis = this;
  axios
    .post(apiUrl.api_url + "getRolePermissionData", {
      role_id: data.role_id
    }).then(
      result => {
        this.permid = result.data;
        var list = [];
        result.data.forEach(function(value) {
          //by using tempthis variable we provided the current access to the checkedPerm_Id array which not accessible from out of the function which is getRoleRowData
          tempthis.checkedPerm_Id.push(value.perm_id);
          list.push(value.perm_id);
        });
      },
      error => {
        console.error(error);
      }
    );
  this.addrole = data;
},

0๐Ÿ‘

See the following example, using simulation data

var app = new Vue({
  el: '#app',
  data () {
    return {
      listPermissionData: [],
      checkedPerm_Id: []
    }
  },
  created () {
    setTimeout(_=>{
      //Here simulates axois to request Permission data
      this.listPermissionData = [
        {perm_id:1,perm_name:'perm_name1'},
        {perm_id:2,perm_name:'perm_name2'},
        {perm_id:3,perm_name:'perm_name3'},
        {perm_id:4,perm_name:'perm_name4'},
        {perm_id:5,perm_name:'perm_name5'}
      ];
      
      //Here simulates axois to request Selected Permissions (result.data)
      var selected = [
        {perm_id:2,perm_name:'perm_name2'},
        {perm_id:5,perm_name:'perm_name5'}
      ]
      
      this.checkedPerm_Id = selected.map(o=>o.perm_id)
    },1000)
  }
})
	<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<div id="app">
  <div class="form">
  <h6>Permissions</h6>
    <span v-for="perm_name_obj in listPermissionData">
      <input type="checkbox" class="perm_id" v-bind:value="perm_name_obj.perm_id" name="perm_id" id="perm_name" v-model="checkedPerm_Id"> {{perm_name_obj.perm_name}}<br>
    </span>
    <span>Checked names: {{ checkedPerm_Id }}</span>
  </div>
</div>

Leave a comment