inyansuta
2 months ago
337
4
Vue

Incorrect rendering of the parent component

Posted 2 months ago by inyansuta

I spent two days looking for the cause of the huge number of unnecessary rendering of hundreds of components in a large project (using Vuex). Below is an example of behavior I don't understand.

// app.js
window.app = new Vue({
    el: '#app',
    data() {
        return {
            rootVariable: 0,
        }
    },
});

// parent.vue
<template>
    <child></child>
</template>

<script>
    import Child from "./Child";

    export default {
        name: 'Parent',
        components: {Child},
        data() {
            return {}
        },
    }
</script>

// child.vue
<template>
    <div>
        {{ rootVariable }}
    </div>
</template>

<script>
    export default {
        name: 'Child',
        props: {
            rootVariableFromParent: {},
        },
        data() {
            return {
            }
        },
        computed: {
            rootVariable() {
                return this.$root.rootVariable;
            }
        },
    }
</script>

The above example works fine. Whenever the variable in the application root (rootVariable) changes, Vue starts rendering only the child component.

// ok - vue rerender child component
window.app.rootVariable++;

When I ONLY try to pass a variable in the parent component using props, each time the root variable changes, the parent component is also rendered.

// updated parent.vue
<template>
    <child
        :root-variable-from-parent="$root.rootVariable"
    ></child>
</template>

// in console
// Vue rerender parent component
window.app.rootVariable++;

In other words, if a child component accesses a variable in the application root, changing that variable will render that internal component. However, if this variable is passed using props, then when changing the variable in the application root, this parent component will also be rendered.

Why?

Please sign in or create an account to participate in this conversation.