Exporting a function from Vue's `<script setup>` is similar to exporting from a module

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.

Answer №1

To make the function accessible, you can utilize the defineExpose macro and then apply a template reference to the child component:

<!-- TestHeading.vue -->
<template>
  <h1>{{ title }}</h1>
</template>

<script setup>
import { ref } from 'vue';
const title = ref('title');

 function set_title(new_title) {
  title.value = new_title;
}

defineExpose({
  set_title
})
</script>
<!-- TestDocument.vue -->
<template>
  <TestHeading ref="heading" />
  <p>Main text</p>
</template>

<script setup>
import { TestHeading } from '../components/TestHeading.vue';

const heading = ref()

heading.value.set_title('new title');
</script>


However, it is advisable to utilize a prop or slot instead:

<!-- TestHeading.vue -->
<template>
  <h1>
    <slot/>
  </h1>
</template>

<script setup>

</script>
<!-- TestDocument.vue -->
<template>
  <TestHeading >
     {{title}}
  </TestHeading> 
 <p>Main text</p>
</template>

<script setup>
import { ref } from 'vue';
import { TestHeading} from '../components/TestHeading.vue';

const title = ref('title');

</script>


Answer №2

Surprisingly, not only can you include a <script setup> tag in a Vue SFC, but you can also have a regular <script> tag.

Within this non-setup script tag, you can export normally and those objects can be imported from other modules.

// MyChildComponent.vue
<script setup>
// Plenty of Vue logic
</script>

<script>
export function myFunction() {};
</script>

<template>
// Plenty of Vue markup
</template>

<style scoped>
// Plenty of Vue style
</style>
// MyParentComponent.vue
<script setup>
import MyChildComponent, { myFunction } from "MyChildComponent.vue";
</script>

<template>
// Plenty of Vue markup
</template>

<style scoped>
// Plenty of Vue style
</style>

Simple? Definitely!

Unconventional? 🤷‍♂️

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Component triggering a dirty state in Vue

On my Vue page, I have input fields and would like to display a message when any of these input fields are changed. In Angular, this can be done easily with the isDirty function, but in Vue, this functionality is not available. Is there a method to captur ...

Angular HttpClient request fails to initiate

Overview: A button click on a form triggers the methodForm within the component. methodForm then calls methodService in the service layer. methodService is supposed to make an HTTP POST request. Problem: The HTTP POST request is not being made. However, me ...

When attempting to inject a provider from the same module, the dependencies cannot be resolved

Bug Report Current Issue Encountering an error when trying to instantiate the PaymentProcessorModule: Error: Nest cannot resolve dependencies of the PaymentProcessor (?, PaymentsService, ProcessingService). Please ensure that the TransactionsService argum ...

Stop JSON.parse from shuffling the order of an object

When working on my web application, I retrieve a JSON string from the server and store it in a variable called greetings: var greetings = '{"2":"hoi","3":"hi","1":"salam"}' I have obser ...

Searching for the way to access the values of a nested object's ref in Vue JS?

Within my Vue data object, I store a reference to a structure called Plot. It has properties for length, width, and acreage. interface Plot { length: number, width: number, acreage: number } const model = { plot: ref<Plot[]>([]), }) When fe ...

An SQL query that functions flawlessly in STUDIO 3T, yet fails to execute in Express.js

I encountered a puzzling situation where a query that functions perfectly in STUDIO 3t fails to retrieve any data in express js. Below is the code comparison: STUDIO 3t Query: db.getCollection("tickets").find({ $and: [ {"TCKT_CRTE_DTTM" : { ...

Autocomplete component fails to trigger onChange event upon losing focus in Mui framework

When using a Mui Autocomplete with the properties of multiple and freeSolo, a situation arises where pressing Return triggers an onChange event. However, when tabbing out of the Autocomplete widget, the typed text remains without updating the state of the ...

Enhancing table field functionality in Backbone.js

In my Backbone application, I am trying to debug the following code outline. window.TableView = Backbone.View.extend({ initialize: function() {... .. .. ... }); }, selectRow: function() { ... ... .. }, render: function() { // ...

Issue with ESLint arises following the installation of npm create-react-app package

ESLint is showing Invalid Options: - Unknown options: env, parserOptions, rules. The 'parserOptions' has been removed and you should now use the 'overrideConfig.parserOptions' option instead. Similarly, the 'rules' have been r ...

Utilizing various AngularJS filters with multiple input sources

Looking to enhance my user array filtering process with two input boxes. Here's how the array is structured: $scope.users = [{ id: 1, fname: 'Sophia', lname: 'Smith', email: '<a href="/cdn-cgi/l/email ...

JavaScript: Creating Custom IDs for Element Generation

I've been developing a jeopardy-style web application and I have a feature where users can create multiple teams with custom names. HTML <!--Score Boards--> <div id="teamBoards"> <div id="teams"> ...

Understanding the getJSON MethodExplaining how

$.getJSON( main_url + "tasks/", { "task":8, "last":lastMsgID } I'm a bit confused about how this code functions. I'm looking for a way to retrieve messages from a shoutbox using a URL or some sort of method that the function here ...

What steps can I take to convert my React class into a function in order to incorporate Material UI components effectively?

With Emailjs set up successfully, my next step is integrating Material UI text fields (link: https://material-ui.com/components/text-fields/#text-field) to enhance the design of my project. The challenge I'm facing is incorporating Material UI classe ...

Is there a way to deactivate all dot inputs on number type input in vue.js 2?

Here is an example of my HTML code: <div id="app"> <input type="number" v-model="quantity"/> </div> This is how my Vue component looks: new Vue({ el: '#app', data: { quantity: '' }, watch: { quanti ...

Determine the absence of values in a randomly generated array and identify the quantity of missing values

My current challenge involves solving CodeSignal projects, and I recently encountered a problem where a random array of numbers is given, requiring me to determine how many additional numbers are needed to make the array consecutive. For instance, if the ...

Utilize the sortable script for dynamically loaded items via AJAX

For the drag and drop feature on my website, I am using jQuery sortable. I have a button that displays results with items on the screen. These items can be dragged and dropped into various sections. The issue I'm facing is that if I include the sort ...

Content is missing from the response of the AngularJS $http request

Attempting to retrieve content from a website using Angular's $http service. The request seems to be successful as console.log(response.data) displays most of the content but is missing some parts. Check out my code below: $http = angular.element(doc ...

When attempting to access endpoints from other computers, the connection to Express.js is being refused

I have set up an Express server and React for the frontend. The express server is running on port 5000 and React on port 3000. Additionally, I am using JWT tokens for authentication. When I login to the app from the computer it is running on, everything w ...

Yeoman - Storing global settings efficiently

I have recently developed a Yeoman generator and am now looking to incorporate prompts for certain global configurations. My goal is to have the generator prompt users for their GitHub username and token during the initial run, and then somehow store this ...

Comparison Between React-Redux mapStateToProps and Inheriting Props from ParentsIn the

Excuse my lack of experience, but I am currently delving into the world of react-redux and trying to grasp the concepts as I progress. Situation: In my main component within a react-redux application, I have the following snippet at the end: function map ...