Mokkapps Logo

Vue Tip: Use Two Script Blocks

Michael Hoffmann (Mokkapps) - Senior Frontend Developer (Freelancer)
February 14, 2022
1 Minuten Lesezeit
- Ansichten

If you are using the new <script setup> syntax, you may run into a case where you need some Options API functionality. In this case, it’s possible to add an additional <script> block to your component. Vue will mix the two together for you, so the Composition API code and Options API code can remain separate.

You may need a regular <script> block in these cases:

  • Use the Options API to declare options that cannot be expressed in <script setup>, for example, inheritAttrs or custom options enabled via plugins.
  • Run side effects or create objects that should only execute once because setup() is run for every component.
  • Declare named exports which allow exporting multiple things from one file.
// Normal <script> using Options API, executed in module scope (only once)

// Here you can declare additional options
export default {
  name: 'MyComponent',
  inheritAttrs: false,
  customOptions: {}

<script setup>
// Composition API: executed in setup() scope (for each instance)
import { ref } from 'vue';
console.log('Setting up new component instance');
const count = ref(0);

This feature is officially supported and documented.

If you liked this tip, follow me on Twitter to get notified about new tips, blog posts and more content from me.

Alternatively (or additionally), you can also subscribe to my newsletter.

Sie haben einen Fehler in diesem Artikel gefunden? Sie möchten gerne etwas klarstellen, aktualisieren oder hinzufügen?

Alle meine Artikel können auf Github editiert werden. Jeder Fix ist willkommen, egal wie klein er sein mag!

Ändern auf Github