Subscribe on changes!

Expose variables in regular script block to template when using script setup

avatar
Aug 17th 2021

What problem does this feature solve?

When using script setup, you might want to define a variable in a regular script block and then use it in the template. Some examples where this are useful are when initializing the variable requires an expensive calculation or you want to share some kind of state between multiple instances of the same component (e.g. a counter for unique IDs). Currently this is a bit awkward because you have to initialize it in the regular script block and then alias it in the script setup block to be able to access it in the template.

What does the proposed API look like?

Variables in regular script blocks are automatically exposed to the template when combined with a script setup block.

avatar
Aug 17th 2021

I'm not sure this is safe to do this automatically without creating a breaking change. Having to alias it seems like a very reasonable way to do it since having expensive operations inside of an SFC is not something that happens that often:

<template>
  <h1>{{ msg }} {{ name }}</h1>
</template>

<script>
  const _name = 'my name'
</script>

<script setup>
// aliasing here
const name = _name
const msg = 'Hello World!' + name
</script>
avatar
Aug 17th 2021

I think this is reasonable since it aligns with the compilation mental model and we already expose imports from normal <script> blocks as well.

avatar
Sep 13th 2021

@henribru I meet the same issue, especially the first one with exported variable. Can we re-open this issue co it won't be overlooked?

avatar
Sep 15th 2021

I'm not able to reopen the issue but I made a new issue specifically for that first problem: https://github.com/vuejs/vue-next/issues/4600