如果我为每个组件使用两个 onMounted() 会有问题吗?

dec*_*coy 3 vue.js vue-component vuejs3 vue-composition-api vue-script-setup

我只见过每个组件有一个 onMounted() 的示例。
我想对每个功能使用 onMounted() 。
有什么问题吗?

我的组件.vue

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

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

// Feature B
onMounted(() => {
  // Do something.
});
</script>
Run Code Online (Sandbox Code Playgroud)

Bou*_*him 6

如果您打算将功能提取到单独的可组合函数中,您可以这样做:

<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>
Run Code Online (Sandbox Code Playgroud)

然后 :

<script setup>
...
useFetch();

useCounter();

</script>
Run Code Online (Sandbox Code Playgroud)