[Vuejs]-Select from JSON, use radio input in Vue.js

0👍

You can do something like this.

You need to splice existing item each time so new value added.

Main part was searching item and removing and you can do it by looping through current items and find index of existing item and remove it so new value can be updated.

check below code.

var attributes = [{
    "name": "Color",
    "variant": [
      {
        "name": "Red"
      },
      {
        "name": "Green"
      },
      {
        "name": "Blue"
      }
    ]
  },
  {
    "name": "Size",
    "variant": [
      {
        "name": "L"
      },
      {
        "name": "XL"
      },
      {
        "name": "XXL"
      }
    ]
}];

new Vue({
  el: '#app',
  data: {
    message: 'Hello Vue.js!',
    attributes: attributes,
    selectedData:[]
  },
  methods:{
     setValue( name, value) {
      //console.log(name,value);
      
      var self = this;
      this.selectedData.forEach(function(val, index){
      
         if(val['name'] == name) {
           self.selectedData.splice(index, 1);
           return false;
         }
      });
      
      
      this.selectedData.push({
        "name": name,
        "variant": 
          {
            "name": value
          }
      });   
     }
  }
})
<!DOCTYPE html>
<html>
<head>
<script> console.info = function(){} </script>
<script src="https://vuejs.org/js/vue.js"></script>
<script src="https://code.jquery.com/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
  <style>.half{width:50%;float:left;}</style>
</head>
<body>
  <div id="app">
    <div class="half">
     
        <div class="form-group" v-for="(attribute, index) in attributes">
    {{attribute.name}}
           <div v-for="(variant, vindex) in attribute.variant">
                <label>
                <input @click="setValue(attribute.name, variant.name)" type="radio"
                   :value="[{name: attribute.name, variant:variant.name}]"
                   :id="'radio' + vindex"
                   :name="'group' + index">
                   {{variant.name}}</label>
            </div>  
           </div>          
      </div>
          <div class="half">
      <pre>{{ selectedData }}</pre></div>
   </div>
  </body>
</html>

Leave a comment