Using Vue.JS to import a custom module

I've put together a module called greetings.js, structured like this:

function greetings() {
  this.hello = function() {
    return 'hello!';
  }

  this.goodbye = function() {
    return 'goodbye!';
  }
}

module.exports = greetings;

Next, I brought it into main.js within the VUE.JS framework as shown below:

import greetings from './assets/js/greetings';
Vue.use(greetings);

Now, when trying to utilize it in my components, an error occurs:

  mounted() {
    this.greetings.hello();
  }

ERROR: Error in mounted hook: "TypeError: Cannot read property 'hello' of undefined"

Any tips on how to resolve this issue and successfully use my greetings module? Appreciate any assistance!

Answer №1

The greetings.js file should be structured as follows:

export default {
  sayHello() {
    return "hello";
  },
  sayGoodbye() {
    return "goodbye!";
  }
};

To use this file in any other, simply import it like so:

import greetings from './assets/js/greetings';

You can then call any function you wish to utilize. Make sure to remove the line Vue.use(greetings);

Answer №2

When you want to register a custom plugin using Vue.use(), remember that it must include an install() function that Vue will call. Here's what the docs say:

To create a Vue.js plugin, make sure it has an install method. This method will receive the Vue constructor as the first argument, along with any additional options.

Check out the example provided at this link to learn about all the options you have for creating your own custom plugin: https://v2.vuejs.org/v2/guide/plugins.html

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

Having trouble importing SVG as a React component in Next.js

I initially developed a project using create-react-app with Typescript, but later I was tasked with integrating next.js into it. Unfortunately, this caused some SVGs throughout the application to break. To resolve this issue, I implemented the following pa ...

Improving the method for calculating the sum of a property value within an array

I have a similar structure as below: $scope.traveler = [ { description: 'Senior', Amount: 50}, { description: 'Senior', Amount: 50}, { description: 'Adult', Amount: 75}, { de ...

``Where can I find information on setting a timeout for a node.js application

Is it feasible to implement a timeout for running node.js? I am faced with the issue of connecting to external services that occasionally do not respond, causing my script to hang and the node.js process to freeze. I am seeking a solution to enforce the t ...

React - updates to server values do not display in DOM right away

When I work from the client side, I have a modal in my HomeComponent that allows me to select an element. My goal is to then display that selected element within the same HomeComponent (in the productosEnVenta function). The element chosen in the modal is ...

What is the process for invoking a JavaScript function and storing form data in a text file within an HTML document?

My HTML code is here..... <!DOCTYPE html> <html> <title>Plot</title> <head> <script type="text/javascript" src="d3.min.js"></script> <script> function filter() { var choice = document.ge ...

Challenges with the Parent Element in jQuery appendTo Operation

First of all, I want to express my gratitude for your help in advance. My goal is to place a hovering div on top of every anchor tag present on a webpage. I aim to calculate the offset, height, and width of each element, then create a new div with CSS set ...

How can one utilize electron's webContents.print() method to print an HTML or text file?

Electron Version : 2.0.7 Operating System : Ubuntu 16.04 Node Version : 8.11.1 electron.js let win = new BrowserWindow({width: 302, height: 793,show:false}); win.once('ready-to-show', () => win.hide()); fs.writeFile(path.join(__dirname ...

Handling complex JSON data in KendoUI Grid with varying keys

I have come across a challenging issue with a complex SLC loopback query and the JSON format it returns. Despite my best efforts to find a solution, I seem to be struggling to grasp some of the answers or perhaps I am approaching the problem from the wrong ...

Jquery AJAX promise will consistently fail when the ajax call encounters an error

I am facing an issue with a loop that involves multiple ajax requests. Each ajax request is handled through the always callback and pushed into a promises array. Finally, $.when is used on always. If all $.ajax calls are successful, the $.when.apply($, p ...

Use jquery to modify fields

Looking to modify certain contact form fields using jQuery. Here is the original code: <label for="avia_3_1">Name <abbr class="required" title="Required">*</abbr></label> This is the jQuery I have implemented. There is a dropdown ...

At times, Mongoose may return null, while other times it returns data frequently

I have designed a unique mongoose schema for managing contacts, with a custom defined ID. Here is the schema structure: const mongooseSchema = new mongoose.Schema({ _id:{ type:String, unique:true, required:true }, firstN ...

Incorporating a div element dynamically into a cell within a datatable with JavaScript

Is there a way to insert a div inside a td element within a datatable using the given HTML code? table = $("#workLocation-table").DataTable({ data: mainArray, "columnDefs": [ { className: "details-control" , "target ...

Locating a specific entry in a custom object array based on a property

Currently working on an Angular 2 app using Typescript and encountering a challenge. There is a service that retrieves an array of questions structured like this: export class Question { constructor(public id: number, public quest ...

Tips for streamlining the filter function using replace and split:

Currently, I am utilizing a filter function alongside replace() and split(). Here is the code snippet: jQuery('table .abc').filter((i, el) => jQuery(el).text(jQuery(el).text().replace('a', 'b').split(' ')[0] + &ap ...

Setting up global Axios configuration with authentication in NuxtJS using VueJS

In my quest to configure Axios globally with authentication in NuxtJS - VueJS (primarily NUXTJS), I am facing a challenge. What I aim for is pretty straightforward: If a user is logged in and has a token in $store, I want Axios to use this token. If the u ...

Constantly showing false values in AngularJS Firebase array objects

Encountering an issue with retrieving data from Firebase. When viewing console.log($scope.statusbaca), it shows 2 queries, true and false. However, in the app it only displays false. Apologies for any language barriers as English is not my first language. ...

How to Convert Python Lists into JavaScript?

octopusList = {"first": ["red", "white"], "second": ["green", "blue", "red"], "third": ["green", "blue", "red"]} squidList = ["first", "second", "third"] for i in range(1): squid = random.choice(squidList) octopus = random. ...

Using the `channel.client` function in Discord.JS without displaying bot client details - a guide

Utilizing the ChannelUpdate event in Discord.js for my bot, I am able to log the previous information of a channel when it is updated, including details such as name, ID, type, creator, etc. However, I encountered an issue where using channel.client.user ...

The JSON data appears to be correct, yet it is not functioning properly when transmitted to X

I have a JSON object that has been validated using https://jsonlint.com/. However, I am encountering an error when trying to use this JSON with the Xero API as shown below. { "Type": "ACCREC", "Status": "AUTHORISED", "DueDate": "2021-12-11T14:24:0 ...

The Material-UI table spills out of its designated container

My material-ui table is resizing and scrolling horizontally without issue, but the table element and its contents are overflowing off the right side of the page. Check out this gif to see the behavior: https://i.stack.imgur.com/lXuHj.jpg Additionally, her ...