Home  >  Q&A  >  body text

How to stop execution of rest of setup script in Vue 3 composition api

<p>I have a subpage with similar code</p> <pre class="brush:php;toolbar:false;"><script setup> import { inject } from 'vue' import { useRouter } from 'vue-router' const router = useRouter() const isSomething = inject('isSomething') if (!isSomething.value) { router.replace('/somepage') } // rest of setup script with a lot of code // like api data fetch </script></pre> <p>It works, so if the condition is false, it will redirect. The problem is - Vue still does the rest of the script setup, like getting all the API data events it doesn't need. </p> <p>Is there a way to "stop" a script setup? </p> <p>I can't use middleware for this because my condition is based on a ref variable provided by the parent page. If I try to inject it at router hook level - it is undefined. </p>
P粉032977207P粉032977207414 days ago510

reply all(1)I'll reply

  • P粉334721359

    P粉3347213592023-09-01 09:54:24

    It's done just like anywhere else in JavaScript:

    if (!isSomething.value) {
      router.replace('/somepage')
    } else {
      // rest of setup script with a lot of code
    }

    The presence of "a lot of code" indicates that the view component can be refactored to contain only the code necessary for routing, and the rest can be extracted into nested components.

    reply
    0
  • Cancelreply