Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any problem if I use two onMounted() per one component?

I have only seen examples of one onMounted() per one component.
I'd like to use onMounted() for each feature.
Is there any problem?

MyComponent.vue

<script setup>
import { onMounted } from 'vue';

// Feature A
onMounted(() => {
  // Do something.
});

// Feature B
onMounted(() => {
  // Do something.
});
</script>
like image 561
decoy Avatar asked Oct 28 '25 04:10

decoy


1 Answers

You could do that if you plan to extract the features to separate composable functions :

<script setup>

import { onMounted } from 'vue';

//fetch data feature
const data = ref([])
onMounted(()=>{
   fetch('someurl').then(response => response.json())
  .then(res => data.value=res.data)
  .catch(error => console.error(error));
})


//counter feature
const count=ref();
onMounted(()=>{
  count.value=0
})
</script>

then :

<script setup>
...
useFetch();

useCounter();

</script>
like image 157
Boussadjra Brahim Avatar answered Oct 30 '25 06:10

Boussadjra Brahim



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!