Creating reusable functions in VueJS that can be accessed globally by all child components

Looking for assistance in setting up a universal function that can be accessed across all my Vue files.

For example, when using this code snippet in a Vue file:

@click="ModalShow.show('my-create')" 

I have defined the following constant in my app.js:

const Modals = {
    show(screen) {
      alert(screen);
      // additional logic to be executed
    },
};

However, I am encountering the error message:

TypeError: undefined is not an object (evaluating '_ctx.Modals.show')

Any ideas on what might be missing? This is within a Vue project utilizing the composition API.

Answer №1

To pass functions to child components in Vue, you can utilize the provide/inject feature. Start by providing your function from the main app (or parent component) to the child components.

const Modal = {...}
const app = createApp({})
app.provide('Modal', Modal)

Then, you can inject this function into your component like so:

import { inject } from 'vue'

export default {
  setup() {
    const Modal = inject('Modal')
    return { Modal }
  }
}

You can also achieve this using the script setup syntax:

<script setup>
import { inject } from "vue";
const Modal = inject("Modal");
</script>

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

Is there a way to simulate a KeyboardEvent (DOM_VK_UP) that the browser will process as if it were actually pressed by the user?

Take a look at this code snippet inspired by this solution. <head> <meta charset="UTF-8"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> </head> <body> <script> $(this). ...

Using Angular BehaviorSubject in different routed components always results in null values when accessing with .getValue or .subscribe

I am facing an issue in my Angular application where the JSON object saved in the service is not being retrieved properly. When I navigate to another page, the BehaviorSubject .getValue() always returns empty. I have tried using .subscribe but without succ ...

Setting up Electron to utilize TypeScript's baseUrl can be achieved by following a few simple steps

In TypeScript, there is a compiler option known as baseUrl that allows you to use non-relative paths, like: import Command from "util/Command" as opposed to: import Command from "../../../util/Command" While this works fine during compilation, TypeScri ...

What strategies can I use to refactor this controller in Angular 1.5 to make it more concise and efficient

I am encountering an issue with a component I have that contains a button. Whenever the button is clicked, it triggers one of two backend services depending on where the component is located. To achieve this, I am currently passing a flag to the component ...

Exploring the possibilities of utilizing JavaScript within TypeScript

My dynamic javascript object holds all the resources (translation strings) for my app. Here's how it is structured: var ResourceManager = (function () { function ResourceManager() { var currentLanguage = $('#activeLanguage').htm ...

When the key code is equal to "enter" (13), the form will be submitted

When I press the Enter key, I want to submit a form if there are no error messages present. Here is the function I have created: $(targetFormID).submit(function (e) { var errorMessage = getErrorMessage(targetDiv); if (e.keyCode == 13 && errorMessa ...

Getting the current URL in InApp browser on Phonegap 3.0: A quick guide

Hey there, I am having trouble retrieving the current URL of an in-app browser when clicking the close button or at any time after loading a URL. Here's my code: var ref = window.open('http://google.com', '_blank', 'hidden=y ...

Error: Route configuration must include a "path" in [vue-router]

I found an official example that I'm trying to follow, but I keep getting a blank page with a JavaScript error. vue-router.esm.js?fe87:10 Uncaught Error: [vue-router] "path" is required in a route configuration. Below are the two pages I am workin ...

Is there a way for me to immediately send data after receiving it?

When I try to perform onPress={() => kakaoLosing() I am attempting to retrieve data (profile) from getProfile using async await and immediately dispatch that data to KAKAOLOG_IN_REQUEST, This is my current code snippet: import { ...

Unable to retrieve information from req.body, however able to retrieve data from req.params

I'm facing an issue with my code where I am not able to retrieve user data from req.body as it returns undefined. However, I can successfully access the required information from req.params. Can anyone provide guidance on how to resolve this issue? co ...

Building a stunning Vue application with an interactive Kendo diagram

I'm currently following the guidelines provided on https://www.telerik.com/kendo-vue-ui/components/diagram/ to implement a diagram in my standalone Vue application using .vue files. However, I encountered an issue where it fails at kendo.dataviz, sta ...

Prevent the browser back button from being used in a web application that requires CLIENT_CERT authentication

My website utilizes CLIENT_CERT JAAS authentication and is compatible with IE7. After logging out, when I return to the home page and click on the back button, I want to stay on the same non-secure page. I have been able to achieve this using the history. ...

MVC4: Exploring the Strategy for Handling Nested Ajax Requests

Creating a form in a web application, I implemented filtering data based on user selection using AJAX to retrieve JSON nested data from BankPlans table. However, I encountered an issue when attempting to fetch all required documents for each bankID from an ...

What sets cross-fetch apart from isomorphic-fetch?

According to the Redux documentation, cross-fetch is the preferred choice, whereas most other sources recommend using isomorphic-fetch. What sets these two apart? ...

Vue-powered carousel having trouble rotating properly

I recently came across a carousel created using vanilla javascript and html. I attempted to convert it to Vue, but encountered some challenges. The carousel is supposed to dynamically pull images from a SharePoint list. However, in my version, the images a ...

Tips for composing a hyperlink within a property

I'm a newbie to Vue.js and facing a challenge with assigning a property to a link. I'm unsure of how to write the "counter" variable from "data" in order for it to properly function as intended. export default { name: 'app', data ( ...

Tips for creating a cookie for an alternate website upon launching a new browser tab

Hey there, I'm facing an issue that I could really use some help with. To give you some context, I'm working on a project using Angular and TypeScript. My goal is to implement single sign-on functionality for multiple websites within one applica ...

The 'userEvent.type' function in React Testing Library is failing to update the input value in a Material UI TextField component that has

I am currently facing an issue with a material UI TextField element that is meant to track the latitude value. The requirement is for the latitude to fall within the range of -90 to 90 degrees. I have implemented a unit test as a validation measure, howeve ...

Authenticating Users with Laravel and Vue.js

In my Vue.js application, I have implemented a login system. The main script in my main.js file includes the necessary imports and configurations: import Vue from 'vue'; import NProgress from 'nprogress'; import Resource from 'vue ...

What is the best way to change the value of a div using JavaScript?

i could really use some assistance, i am trying to ensure that only the selected template is shown on the screen, while all others are hidden. The expected outcome should be to replace the values of: <div class="city">City<span>,< ...