Home > Blockchain >  trigger click event based on count of JSON
trigger click event based on count of JSON

Time:10-15

I have a b-dropdown in my parent.vue where I select an item and send Props (e.g. 1111, 2222, ... and so on) to my child.vue.

Now I need to check e.g. if my props-value is 1111 how many rows (my definition of rows in this case are 0 and 1 so two rows) are in this JSON-Object and than trigger my click-event based on this count to add the amount of elements to my template.

My question is if this is possible and if yes how to do that?

Thank You!

in my template of child.vue:

<div class="mt-2">
  <b-button @click="addElement" variant="block">Add element</b-button>
</div>

my script:

import json from './json/json.json'

data() {
  return {
    inputs: [{}]
    json: json,
  }
}

methods: {
  addElement() {
    this.inputs.push({});
  },
}

props: ["item"]

my JSON:

[
    {
        "1111": {
            "0": {
                "Number": 1234
            },
            "1": {
                "Number": 4321
            }
        }
    },
    {
        "2222": {
            "0": {
                "Number": 6789
            },
            "1": {
                "Number": 9876
            }
        }
    }
]

CodePudding user response:

You can get object size by Object.keys({"0": {"Number": 1234}, "1": "x"}).length.

Applied to your code:

addElement() {
   if(this.item === '1111'){
     for(let key in this.json[0]['1111'])
         this.inputs.push({});
     }
     //or
     this.addSomething(Object.keys( this.json[0]['1111'] ).length)

   }    
},

CodePudding user response:

You can try with for (variable in object) {statement} and mounted hook:

Vue.component('Child', {
  template: `
    <div class="mt-2">
      <h3>child</h3>
      <p>{{ inputs }}</p>
    </div>
  `,
  props: ["item"],
  data() {
    return {
      inputs: [],
    }
  },
  methods: {
    addElement(el) {
      for(let key in el) {
        this.inputs.push(el[key])
      }
    }
  },
  mounted() {
    this.addElement(this.item)
  }
})

new Vue({
  el: '#demo',
  data() {
    return {
      json : [
        {"1111": {"0": {"Number": 1234}, "1": {"Number": 4321}}},
        {"2222": {"0": {"Number": 6789}, "1": {"Number": 9876}}}
      ]
    }
  }
})

Vue.config.productionTip = false
Vue.config.devtools = false
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo">
  <Child :item="json[0]['1111']" />
</div>

  • Related