Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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>

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading