javascriptvue.jsbootstrap-vuebootstrap-table

Vue.js Bootstrap table - pass data between Parent and Child component


I have 2 components: Parent and Child. In both components, I'm using Bootstrap tables and their 'items' and 'fields' come from API. The Child component should pass data (true or false, for each table row) to the Parent component. I want to assign this data from the Child component to the Parent component bootstrap table row object. You can see my code below.

So, the problem is that the v-if statement doesn't work. It seems like the object 'state' is assigned before the component is created because on console.log I can see that the new 'state' object is there and filled correctly with true/false but in DOM the situation is different, the state is undefined.

Anyone who can help how can I set the 'state' object and make it works?

Parent component:

<template>
    <b-table v-else :items=“customItems” :fields="fields" responsive>
        <template v-slot:cell(config)="row">
            <child-component
              @onitembind='isSingleRow'>
            </child-component>
        </template>       
    </b-table>
</template>

<!-- Checkbox column --> 
<template v-slot:cell(labelCheckbox)="row">
    <div class="label-checkbox" v-if="row.item.state">
        <span><i class="fa fa-angle-up text-primary">
    </div>
</template>



<script>
    methods: {
        isSingleRow(event) {
            this.singleRow.push(event);
            for(let i in this.customItems){
                this.customItems[i].state = this.singleRow[i]
                console.log('EHO ', i, ' ', this.customItems[i]);
            }
        }
    }
</script>

Child component:

<script>
    created() {
            this.tableRowsLength()
    },

    methods: {
        tableRowsLength () {
                if((this.innerTableItems.length) != 1){
                    this.$emit('onitembind', true)
                } else{
                    this.$emit('onitembind', false) 
                 }
            }
    }
</script>

Solution

  • In Vue 2, adding properties to an existing object wont be reactive, as Vue wont be able to properly add a getter/setter for the property.

    To get around this you should use the Vue.set/this.$set method.

    this.$set(this.customItems[i], 'state', this.singleRow[i])

    For more information see: https://v2.vuejs.org/v2/guide/reactivity.html#For-Objects