Search code examples
vue.jsvue-componentvuejs3vue-composition-apivue-script-setup

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>

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>