Using Vue.js to import a class with a function and then utilizing it in a child component

I have a component called my-parent. Within this component, I am utilizing a child component named my-child and importing an external class known as MyClass, which includes its own function called exportedFunction. I attempted to implement the solution outlined in this thread: VueJS accessing externally imported method in vue component

In essence, what I have done is used the mounted lifecycle hook along with the referenced function from the imported class. Additionally, within the methods section, I defined a new method that invokes the mounted function from the imported class. Following this, I passed the created method as a property to my child component, where I then attempted to invoke the function using a @click event and passing a parameter.

Below is the current state of my code:

my-parent template:

<template>
    <my-child :exportedFunction="callFunction"></my-child>
</template>

<script>
import MyClass from './MyClass';

export default {
    mounted() {
        exportedFunction()
    },
    methods: {
        callFunction() {
            exportedFunction()
        }
    }
}
</script>

my-child template:

<template>
    <button @click="exportedFunction('hello world!')">Click me!</button>
</template>

<script>
export default {
    props: ['exportedFunction']
}
</script>

MyClass code:

export default class MyClass {
    exportedClass(parameter) {
        console.log(parameter) // expected 'hello world' from child
    }
}

Any assistance would be greatly appreciated!

Answer №1

Why not consider replacing your MyClass component with something simpler like:

my-parent

<template>
    <my-child :triggerEvent="callFunction"></my-child>
</template>

<script>
export default {
    methods: {
        callFunction() {
          console.log('hello');
        }
    }
}
</script>

my-child

<template>
    <button @click="$emit('triggerEvent')">Click me!</button>
</template>

If you still need to use MyClass, you can keep it as it is and have my-parent structured like this:

<template>
  <my-child :triggerEvent="callFunction"/>
</template>

<script>
import MyChild from "./MyChild";
import MyClass from "./MyClass.js";

export default {
  components: {
    MyChild
  },
  data() {
    return {
      myCls: new MyClass()
    };
  },
  mounted() {
    this.myCls.exportedClass("hello my class");
  },
  methods: {
    callFunction() {
      console.log("hello");
    }
  }
};
</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

Chrome now supports clickable circular canvas corners

I have a unique setup with two canvases. I've customized them to be circular by utilizing the border-radius property. The second canvas is positioned perfectly within the boundaries of the first one using absolute positioning. This is where it gets e ...

Tips for designing a sleek and seamless floating button

I attempted to implement a floating button feature that remains in view while smoothly flowing using jQuery. I followed a tutorial I found online to create this for my website. The tutorial can be accessed at this link. However, after following all the ste ...

What is the process for preserving changes made in rest_in_place when inputting a new type?

In my rails project, I've implemented the rest_in_place plugin to enable dynamic data editing. <ul class="offer-completed__edit-details" data-url="<%= enquiry_path(@enquiry) %>" data-object="enquiry"> <li>Contact Name: <span ...

The ng-bind directive is functional when used with a textarea element, but it does not work with

Recently diving into the world of angularjs, I stumbled upon ng-bind and its interesting functionality when used as a directive for textarea: <input type="text" ng-model="review.start"/> <textarea ng-bind="review.start"> </textarea> I ...

Employing DOM manipulation within Vue unit tests as a last resort

What steps should I take to update my unit test in order to accurately validate the following scenario? Method: close(event) { const element = !!event?.target?.closest('#target') if (!element) { this.isVisible = false } }, Jest test: ...

Dealing with onChange value in a date in reactjs is a common challenge that developers

I'm currently working on a basic date input component in React, but I've run into an issue when trying to change the value. Every time I update it, it always displays "1970-01-01". If anyone has any suggestions on how to fix this problem, I woul ...

Converting EDN data to a string and back in Clojure/ClojureScript

When working with JavaScript, one can convert a JavaScript data structure into a JSON string using the following code: JSON.stringify({somedata: { somesubdata: {}}}) Then, to parse it back into a JS data structure, you can use: var my_obj = JSON.parse(" ...

Vue.js mounted hook failing to trigger

Whenever I try to load my App component, the mounted() lifecycle hook doesn't seem to be triggered: <template> <div> <div v-if='signedIn'> <router-view /> </div> </div> </template&g ...

In Angular 5, you can easily prevent interaction with a related button by disabling it when the corresponding reactive

I recently encountered a situation where I needed to implement a reactive form in a component. It looked something like this... form component.html <form [formGroup]="form" class="do-form"> <div formGroupName="dot"> <div class ...

A guide on achieving a dynamic color transition in Highcharts using data values

I am currently working on plotting a graph using high charts and I would like to change the color based on the flag values. I attempted this, however, only the points are changing based on the flag values and the line is not being colored accordingly. Be ...

Key factors to keep in mind when comparing JavaScript dates: months

Check the dates and determine if the enddate refers to the following month by returning a boolean value. Example startdate = January 15, 2020 enddate = February 02, 2020 Output : enddate is a future month startdate = January 15, 2020 enddate = January 2 ...

When properties remain unchanged, they do not hold the same value in a Firestore-triggered Cloud Function

Within my Firestore database, there is a collection named events consisting of documents with attributes such as begin, end, and title. The function in question is triggered when any changes occur within a document. The begin and end fields are both categ ...

"Passing an Empty String as Input in a NodeJS Application

app.post('/register',function(req,res){ var user=req.body.username; var pass=req.body.password; var foundUser = new Boolean(false); for(var i=0;i<values.length;i++){ //if((JSON.stringify(values[i].usernames).toLowerCase==JSON. ...

Struggling with JavaScript conditional statements

Currently, I am in the process of creating a login and registration panel using jQuery and PHP. Essentially, if there are any errors during registration, it sets certain form errors, redirects back to the registration page, the JavaScript identifies these ...

A guide on scheduling automatic data insertion in mongoose.js

I'm working on a website with Node.js and Mongoose, and I could use some guidance on how to automatically insert data into Mongoose with Node.js at specific times. For example, at the end of each month, I want my current data to be stored in the Mongo ...

Issue with Vue canvas $ref not being defined on resize causing error, but oddly still seems to function correctly

Within my application, there exists a tabbed interface. One of the tabs contains a canvas element that dynamically adjusts its size to fit the window whenever it is resized. The functionality works seamlessly at first, but upon switching tabs and returning ...

"I am encountering an issue where I am using React and Express to retrieve data from a database, and although I am able to return an array of

I am working on a React app that communicates with an API using Express. Currently, I am using the GET method to fetch data from a database, and my fetching code looks like this: const posts = []; fetch(URL) .then(response => response.json()) .then(jso ...

Mapping keys in a react component for efficient sorting

I'm facing some challenges when attempting to reorder keys from a state within my map function in React.. The original output is: monday : {1200: {…}, 1500: {…}, 1800: {…}, 2000: {…}, 2200: {…}, 0000: {…}, 0100: {…}, 0500: {…}, 0600: ...

Update a section of my PHP webpage using setInterval()

How can I refresh a PHP value every second using setInterval()? I am familiar with refreshing values in HTML, but now I want to do the same with PHP values. Here is my code: <script> setInterval(function() { <?php $urlMachineOnline = ' ...

I'm experiencing difficulties with a JavaScript slideshow in Vegas

After installing the vegas jQuery plugin to my project using npm, I encountered issues when attempting to use it according to the documentation. Despite linking the required vegas.min.js and vegas.min.css files in my HTML, the plugin doesn't appear to ...