Component Tree Re-rendering
Create a parent component with a couple of child components in Vue.js 3 to illustrate selective re-rendering of components in the VDOM when state changes.
<template>
<div>
<button @click="incrementCounter">Increment</button>
<p>Parent Counter: {{ counter }}</p>
<child-component :counter="counter" />
<static-child-component />
</div>
</template>
<script>
import { ref } from 'vue';
import ChildComponent from './ChildComponent.vue'; // Assuming a child component file
import StaticChildComponent from './StaticChildComponent.vue'; // Assuming a static child component file
export default {
components: {
ChildComponent,
StaticChildComponent
},
setup() {
const counter = ref(0);
function incrementCounter() {
counter.value++;
}
return { counter, incrementCounter };
}
};
</script>
This is the parent component that includes a button to increment the counter state and two child components. The first child component will re-render when the counter state changes, but the second child, being a static component, should not.
<template>
<div>
<p>Child Counter: {{ counter }}</p>
</div>
</template>
<script>
export default {
props: {
counter: Number
}
};
</script>
This is ChildComponent that receives a counter as a prop from the parent component and re-renders whenever the counter value changes due to its reactive dependency on the passed prop.
<template>
<div>
<p>I'm a static component. I do not change.</p>
</div>
</template>
<script>
export default {
// This is a static child component, it does not accept any reactive props and should not re-render when parent state changes
};
</script>
This is StaticChildComponent, which does not receive any props from the parent and does not re-render when the parent's state changes as it has no reactive dependencies.