Home > front end >  Why calling async function inside <script> tags fail in Vue if no lifecycle hooks are used?
Why calling async function inside <script> tags fail in Vue if no lifecycle hooks are used?

Time:12-25

Here is the scenario, I have a component, and inside the script tag I am calling an action

<script>
if (something is true) {
    await store.doSomething()
}
</script>

The component fails to mount.

When I use the onMounted hook, it seems to work.

I am beginner in Vue, but my question is what is really happening when I don't use the hook? and is it always necessary to use hook when making asynchronous calls ?

Put it inside onMounted to get it to work, although ran into other test failures afterwards.

CodePudding user response:

In Vue.js, the onMounted hook is a lifecycle hook that is called after a component has been mounted to the DOM. It is a good place to perform tasks that require the component to be fully rendered, such as making asynchronous calls or interacting with the DOM.

When you use the await keyword inside a script tag, it is not within the context of a function, so the await expression cannot be used. This is why you are experiencing an error when you try to use await outside of the onMounted hook.

It is generally a good idea to use a lifecycle hook or a method when making asynchronous calls in Vue, as this allows you to handle the results of the call in a structured way and avoid potential errors. However, it is not always necessary to use a hook, and you may be able to use other techniques such as event handlers or computed properties to perform asynchronous tasks in your component.

I hope this helps! If you are still having trouble understanding how to use asynchronous calls in Vue, you may want to refer to the Vue.js documentation or seek additional guidance from online resources or a mentor.

CodePudding user response:

  1. Looking at what you wrote as of right now, you should have the Options API like this
<script>
export default {
  mounted() {
    // your code
  },
  setup() {
    // can also use setup here
  }
}
</script>
  1. With Composition API (notice the setup)
<script setup>
onMounted(() => {
  // your code
})
</script>

In 2., if you don't use onMounted it will be run withing the setup lifecycle as shown here.


is it always necessary to use hook when making asynchronous calls ?

Not really, but at the same time it depends on when/how you want it to run. Start by running it into mounted initially yep, easier and safer to understand overall.
Especially since setup does not re-run when re-mounted, can be quite confusing.
It also depends exactly on what is something is true exactly, regarding the lifecycle state.


Pinia and Vitest will get their own things to think about.
I recommend reading the documentation and getting an initial grasp before proceeding.

  • Related