Issue
When I changed something in a Vue nested component and saved it. The Vite HMR will constantly reload the component. And then it caused a warning of vue: Maximum recursive updates exceeded...
Try online Demo on stackblitz. Change something in Child1.vue and save. You can see 101 times same info and a warning in console.
Or code blow with Vue3.x + Vite4.x/5.x:
Child1.vue
<script setup lang="ts">
const emits = defineEmits(['list-change']);
emits('list-change', ['a', 'b', 'c']);
// change something and save
console.log('Child1.vue setup');
</script>
Child2.vue
<script setup lang="ts">
const props = defineProps<{
list: string[];
}>();
</script>
App.vue
<template>
<Child1 @list-change="handleListChange"></Child1>
<Child2 :list="list"></Child2>
</template>
<script setup lang="ts">
import { ref } from 'vue';
import Child1 from './components/Child1.vue';
import Child2 from './components/Child2.vue';
const list = ref<string[]>([]);
const handleListChange = (newList: string[]) => {
list.value = newList;
};
console.log('App.vue setup');
</script>
Thanks for help.
Solution
the problem here is you are calling emits('list-change', ['a', 'b', 'c', 'k', 'o']);
directly on child load , what is happening here is that first app loads that registers function for list-change event then child1 loads and emits that event , now app will listen event and updates list and re-renders whole app cus child2 is using that list , that will again load child1 (cuz of re-render) and again event will be emmited , this loop goes on and on till stack is full.
to prevent this keep emits call in function and call that function in button click
Child1
<script setup lang="ts">
const emits = defineEmits(['list-change']);
function test() {
console.log('Updating List');
emits('list-change', ['a', 'b', 'c', 'k', 'o']);
}
// change something and save
console.log('Child1.vue setup');
</script>
<template>
<button @click="test">TEST 2</button>
</template>
or use onMount
<script setup lang="ts">
import {onMount} from 'vue';
const emits = defineEmits(['list-change']);
onMount(() => {
emits('list-change', ['a', 'b', 'c', 'k', 'o']);
});
// change something and save
console.log('Child1.vue setup');
</script>
Answered By - Darshan Patel
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.