[Vuejs]-Update parent data from recursive child component

0👍

The issue you are having is reactivity in depth, the VueJS documentation provides a good explanation: Reactiviy in Depth – How Changes Are Tracked

There are several ways to trigger the rendering of components. The most obvious one would be this.$forceUpdate(). However it is forcing ever component to to rerendered and I wouldn’t recommend using it. If triggered several times in a short time, it could get slow.

The next two solutions are compared much better only the component without others.

First way to trigger rendering:

<script>
export default {
    data: () => {
        return {
            treeData: []
        }
    },
    methods: {
        updateTree () {
            const treeData = JSON.parse(JSON.stringify(this.treeData))
            this.treeData = []
            this.$nextTick(function () => {
                this.treeData = treeData
            })
        }
    }
}
</script>

Or you could simply use v-if on the parent and call this.$emit('updateTree') from the children:

<template>
    <child-component @update="updateTree" :treeData="treeData" />
</template>

<script>
import ChildComponent from '../components/ChildComponent'
export default {
    data: () => {
        return {
            showTree: true,
            treeData: []
        }
    },
    components: { 'child-component' : ChildComponent },
    methods: {
        fetchAPIData () {
            // ... ajax
            this.treeData = apiResponse
        },
        updateTree () {
            this.showTree = false
            this.$nextTick(function () => {
                this.showTree = true
            })
        }
    },
    mounted () {
        this.fetchAPIData()
    }
}
</script>

Leave a comment