Vue Tip: Use Two Script Blocks

Michael Hoffmann
Feb 14, 2022
| 1 min read
| 814 views
Michael Hoffmann
Feb 14, 2022
1 min read
| 814 views
Script

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, adding an additional <script>
block to your component is possible. Vue will mix the two
together for you, so the Composition API and Options API codes 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.
1
<script>
2
// Normal <script> using Options API, executed in module scope (only once)
3
runSideEffectOnce()
4
5
// Here you can declare additional options
6
export default {
7
name: 'MyComponent',
8
inheritAttrs: false,
9
customOptions: {},
10
}
11
</script>
12
13
<script setup>
14
// Composition API: executed in setup() scope (for each instance)
15
import { ref } from 'vue'
16
console.log('Setting up new component instance')
17
const count = ref(0)
18
</script>
This feature is officially supported and documented.
If you liked this Vue tip, follow me on Twitter to get notified about new tips, blog posts, and more. Alternatively (or additionally), you can subscribe to my weekly Vue newsletter:
New Vue & Nuxt tips delivered to your inbox:
Vue Tip: Speed Up Initial Load Using Async ComponentsFeb 4, 2022
Vue Tip: Use Optional Chaining in TemplatesFeb 19, 2022
Show comments