I would like to export a function from a component from within the "" section and use it in another component.
I tried it like this:
<!-- TestHeading.vue -->
<template>
<h1>{{ title }}</h1>
</template>
<script setup>
import { ref } from 'vue';
const title = ref('title');
export function set_title(new_title) {
title.value = new_title;
}
</script>
<!-- TestDocument.vue -->
<template>
<TestHeading />
<p>Main text</p>
</template>
<script setup>
import { TestHeading, set_title } from '../components/TestHeading.vue';
set_title('new title');
</script>
This just gives me the error: <script setup> cannot contain ES module exports. If you are using a previous version of <script setup>, please consult the updated RFC at https://github.com/vuejs/rfcs/pull/227.
Omitting the "export" I just get:
Uncaught SyntaxError: import not found: set_title in TestDocument.vue.
Is there a way to do it? The component (TestHeading) will only appear once in the whole document, so I should be able to set the title using a global function like this.
Update: Found my workaround, instead of exporting the function, I just set window.set_title = (new_title) => { ... }. Does not seem so clean, but I am probably going to use this unless I find a better way.
It turns out that, in addition to your <script setup> tag you can also have a normal <script> tag in a Vue SFC.
In that non-setup script tag, you are able to export as normal and those objects are importable from other modules.
// MyChildComponent.vue
<script setup>
// Bunch of Vue logic
</script>
<script>
export function myFunction() {};
</script>
<template>
// Bunch of Vue markup
</template>
<style scoped>
// Bunch of Vue style
</style>
// MyParentComponent.vue
<script setup>
import MyChildComponent, { myFunction } from "MyChildComponent.vue";
</script>
<template>
// Bunch of Vue markup
</template>
<style scoped>
// Bunch of Vue style
</style>
Easy? Yes!
Hacky? 🤷♂️
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With