Vue & Nuxt Tips

1 min read

Vue Tip: Expose Properties in a Script Setup Component

Components using script setup are closed by default and will not expose any of the bindings declared inside script setup.

Ask my AI assistant
Michael Hoffmann

Michael Hoffmann

@mokkapps

Vue Tip: Expose Properties in a Script Setup Component Image

Components using Options API or Composition API without <script setup> are open by default.

Only components using <script setup> are closed by default.

If we try to access the public instance of such a component via template ref or $parent chains, it will not expose any of the bindings declared inside the <script setup> block.

We can use the defineExpose compiler macro to explicitly expose properties:

Child.vue
<script setup>
import { ref } from 'vue'

const foo = ref('foo')
const bar = ref('bar')

defineExpose({
  foo,
  bar,
})
</script>

When a parent gets an instance of Child.vue via template ref, the retrieved instance will be of the shape { foo: string, bar: string } (refs are automatically unwrapped just like on normal instances):

Parent.vue
<template>
  <Child ref="child" />
</template>

<script setup>
import { ref } from 'vue'

const child = ref(null)

onMounted(() => {
  console.log(child.value.foo)
  console.log(child.value.bar)
})
</script>

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