What is the process for importing an external function into a Vue component?

Having just started learning javascript and vue.js, I encountered an issue while attempting to add a new function to an existing program.

I decided to store my new function (along with others) in a separate file:

export const MyFunctions = {
MyFunction: function(param) {
    // Performing actions
}
}

After that, I imported the file into the component file and tried to call my function :

<script>
    import {MyFunctions} from "@/components/MyFunctions.js";
    export default {
        name:"Miniature",
        computed: {
            useMyFunction() {
                MyFunction("Please perform some actions!");
            }
        }
    }
</script>

However, when I use the component, I receive an error message

[Vue warn]: Property or method "MyFunction" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property. See: https://v2.vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties.

Despite reading several resources, I can't seem to figure out why it's not working. Any help would be greatly appreciated!

Answer №1

To utilize the MyFunction, which is exported as part of an object, you must access it using dot notation like so:

MyFunctions.MyFunction("Please do some stuff !")

An interactive example demonstrating this concept can be found here: https://codesandbox.io/s/62l1j19rvw


MyFunctions.js

export const MyFunctions = {
  MyFunction: function(param) {
    alert(param);
  }
};

Component

<template>
  <div class="hello">
   {{msg}}
   <button @click="handleClick">Click me</button>
  </div>
</template>

<script>
import {MyFunctions} from "../MyFunctions.js";
export default {
  name: "HelloWorld",
  data() {
    return {
      msg: "Welcome to Your Vue.js App"
    };
  },
  methods:{
    handleClick: function(){
      MyFunctions.MyFunction("Please do some stuff !");
    }
  }
};
</script>

Answer №2

If you want to integrate your javascript files into .vue files, you can simply do so by enclosing them within <script> tags. Remember that Vue.js is essentially javascript, so when troubleshooting, make sure to double-check for any syntax errors. It seems like there may be some confusion with the import and export statements, which can initially seem daunting.

Refer to MDN's Documentation, particularly the section on named exports:

In the module, we could use the following

// module "my-module.js"
function cube(x) {
  return x * x * x;
}
const foo = Math.PI + Math.SQRT2;
var graph = { /* nice big object */ }
export { cube, foo, graph };

This way, in another script, we could have:

import { cube, foo, graph } from 'my-module';
// Utilize your functions efficiently

Answer №3

When exporting, you are essentially exporting an object. To access a specific field or method within this object, you should use the function in the following manner:

MyFunctions.MyFunction("Please perform some actions !");

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

Neglecting a light source in the Three.js framework

Currently, I am in the process of constructing a 3D hex grid and my goal is to integrate a fog of war feature. This is a glimpse of what the grid looks like at present: The lighting setup I have arranged is as follows: // Setting up hemisphere light var ...

In AngularJS, be sure to remove any previous growls before displaying a new one

Working on growl.info() using angularjs and have a query. How can I check if there is already a growl displayed on the screen before adding a new one? The requirement is that when a new growl is triggered, the previous one should be removed from the view. ...

When I send data using axios, I receive the response in the config object instead of the data

Currently, my web app is being developed using NextJS NodeJS and Express. I have set up two servers running on localhost: one on port 3000 for Next and the other on port 9000 for Express. In the app, there is a form with two input fields where users can e ...

Employing passport-steam alongside sails-generate-auth

As I develop my SailsJS application, I am aiming for users to authenticate solely through Steam. I utilized `sails-generate-auth` to set up some boilerplate code with sails routes, but integrating passport-steam has proven challenging. If you are interest ...

Error in Typescript: The property 'children' is not included in the type but is necessary in the 'CommonProps' type definition

Encountering this error for the first time, so please bear with me. While working on a project, I opened a file to make a change. However, instead of actually making any changes, I simply formatted the file using Prettier. Immediately after formatting, t ...

Importing data from a CSV file into an HTML table through JavaScript

I am working on creating a webpage that can load a selected CSV file from the hard drive and then display its contents using HTML tables. My project involves two main components, and I have been focusing on the second component. This part deals with gener ...

Incorporate a Javascript session into MVC 4 Razor for enhanced functionality

I am currently developing an application that allows users to upload files. Before uploading the file, I need to configure the file storage settings. The first step is to read the first ten rows of the file and display them to the user. The user can then p ...

`Count the number of rows needed to accommodate text line breaks within a div element`

Is there a method to determine the number of lines that text breaks into using the CSS property word-break: break-all? For example, if I have a div like this: <div>Sample text to check how many lines the text is broken into</div> And the corr ...

Encountering issues with $.AJAX post in JavaScript, while successful in Advanced Rest Client

My JavaScript code is facing an issue when trying to communicate with the HttpPost service. Interestingly, I can access the same endpoint using the "Advanced Rest Client Application" for Chrome without any problems. However, when I execute my code in the C ...

Convert the jQuery functions click(), hide(), and fadeIn() into their equivalent native JavaScript functionalities

I'm determined to speed up my page by reducing requests. Does anyone have a solution for keeping the functionality of the code below without having to load the entire JQuery library? $("#div1").click(function () { $("#div2).hide(); $("#div3). ...

AngularJS allows you to toggle the visibility of a div at set intervals, creating

I am struggling with the task of showing and hiding a div that serves as an alert for my application. Currently, I am using $interval to create a continuous show and hide action on the div. However, what I aim for is to have the DIV visible for X amount o ...

Ways to conceal a div element when the JSON data does not contain a value

If the value in "desc" is empty, then hide <div24> and <popup-desc>. html <div class="popup"> <div class="popup-top" style="background-color: '+e.features[0].properties.fill+';"> ...

The WebView fails to show up upon triggering the onPress() event

I have a code snippet that creates a card and within this card, I want to load the URL from the card and display a webview using the 'react-native-webview' library. import {View, Linking, TouchableNativeFeedback} from 'react-native'; im ...

Changing the Style of a CSS Module Using JavaScript

Embarking on a journey into Javascript and React, I am currently working on my first React app. My aim is to adjust the number of "gridTemplateRows" displayed on the screen using a variable that will be updated based on data. Right now, it's hardcode ...

Issue with Laravel Echo not responding to pusher notifications

I am currently working on developing a chat application using Laravel and Vue.js. I have encountered an issue where, after sending a message, the event is triggered in Laravel and correctly reflected on the Pusher debug console with the appropriate event c ...

Exploring the capabilities of AngularJS and Spring Boot in web development

I'm encountering a 404 error when trying to load a file in the ng-view route in AngularJS with Spring. As a newcomer to both technologies, I'm struggling to find a solution. app.js app.config(function($routeProvider) { console $route ...

Having trouble with installing Angular JS on my computer

On my machine, I have successfully installed node.js version v0.12.0. However, when attempting to run sudo npm install, I encountered the following errors: npm ERR! install Couldn't read dependencies npm ERR! Darwin 14.0.0 npm ERR! argv "node" "/usr/ ...

Encountered an error when attempting to use the 'removeChild' function on a node that is not a child of the specified node. This issue arose while interacting with an input box

I recently created a todo app with a delete functionality. However, after deleting an element successfully, I encountered an error when typing in the input box stating: Failed to execute 'removeChild' on 'Node': The node to be removed i ...

Execute JavaScript function after the window has finished loading, regardless of any asynchronous downloads

In my app, there is an initialise function that I want to execute only when two conditions are met: first, the window has finished loading ($(window).load()), and second, Typekit has loaded. $(window).load(function() { try { Typekit.load({ act ...

Typescript does not produce unused members

Having an issue with the JS code that TypeScript compiler is generating. Here's an example class: // Class export class UserDTO { Id: number; FirstName: string; LastName: string; DateOfBirth: Date; getFullName(): string { ...