I am trying to export a function from a component within the component itself and then use it in another component.
My attempt looks 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>
However, I am encountering 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.
When I omit the "export" keyword, I receive:
Uncaught SyntaxError: import not found: set_title
in TestDocument.vue.
Is there a way to achieve this functionality? The TestHeading component will only be used once in the document, so I should be able to set the title using a global function like this.
Update: I managed to find a workaround. Instead of exporting the function, I simply set it as
window.set_title = (new_title) => { ... }
. It may not be the cleanest solution, but it works for now unless I come across a better method.