Vue: utilizing shared methods in a JavaScript file

Currently, I am building a multipage website using Vue and I find myself needing the same methods for different views quite often. I came across a suggestion to use a shared .js file to achieve this. It works perfectly when my "test method" downloadModel is a single function, but as soon as I try to split it up, I run into a TypeError: Cannot read properties of undefined(). How can I go about fixing this issue? I apologize for being relatively new in this world. :)

export default {
methods:{  
    downloadModel(id) {
        this.printMessage('Download',id)
    },

    printMessage(string,id){
        console.log(string, id)
    },

} }

Answer №1

Here is a simple example to demonstrate:

In your script.js file :

function displayText(text) {
    this.showMessage('Displaying', text)
}

function showMessage(action, text) {
    console.log(action, text)
}

export { displayText, showMessage };

In your index.html file (for example)

import { displayText, showMessage } from 'js/scripts.js';

Remember that you can omit exporting/importing showMessage if it is only used internally by displayText and not needed outside of the script.

Answer №2

To achieve the desired outcome, you can utilize mixins in your Vue.js components. By defining a shared function in a mixin, multiple components can incorporate this functionality as needed.

For instance:

Mixin
// mixins/shared.vue
export default {
    methods: {
        sharedFunction() {
            console.log("Hi, i'm a shared function!");
        }
    }
}
Component 1
// components/comp1.vue
import SharedFunctionMixin from '../mixins/shared.vue';

export default {
    mixins: [SharedFunctionMixin],
    
    mounted() {
        this.sharedFunction();
    }
}
Component 2
// components/comp2.vue
import SharedFunctionMixin from '../mixins/shared.vue';

export default {
    mixins: [SharedFunctionMixin],
    
    mounted() {
        this.sharedFunction();
    }
}

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

Encountered a problem while trying to upload a video on bunny stream using node.js

Having trouble uploading videos to the Bunny Stream API using Node.js and Axios. Everything else seems to be working fine, like fetching, deleting, changing names, and resolutions of videos. However, when trying to upload a video, consistently receiving 40 ...

What is the best way to capitalize the first letter of a string in JavaScript?

Is there a way to capitalize only the first letter of a string if it's a letter, without changing the case of any other letters? For example: "this is a test" → "This is a test" "the Eiffel Tower" → "The Eiffel ...

Unable to save data to file: ENOENT error - file not found

I'm currently working on creating a folder named "build" that will house numerous map files and JavaScript files. However, I've encountered the following issue. Snippet of the code: "scripts": { "prestart": "d2-manifest package.json manifes ...

Tips for capturing a screenshot of the ESRI Map using Angular

Is there a way to capture a screenshot of the Esri map in its current state on the UI and then convert it into a PDF for download using Angular? Below is my current .ts code, but I am open to any additional suggestions. esri-map.component.html <!-- Map ...

Setting a default value for a select option in Angular 2

I am trying to set a default value for an option, acting as a placeholder using this method. It works in pure HTML, but when I implement it with the *ngFor attribute in Angular 2, nothing is selected. Here is the code I use in pure HTML: <select name= ...

Utilizing HTML and JavaScript to add grayscale effect to images within a table, with the ability to revert to the colored version upon mouseover

Seeking advice on utilizing the mouseover / mouseout event in javascript to implement grayscale on a table. The challenge requires creating a gray image grid (table) using HTML and then incorporating Javascript so that hovering over an image triggers it to ...

Utilize JavaScript to target the specific CSS class

Hello, I am currently using inline JS in my Wordpress navigation menu, redirecting users to a login page when clicked. However, I have been advised to use a regular menu item with a specific class and then target that class with JS instead. Despite searchi ...

Finding an element based on its styling attribute, such as its position on the left or right side

One particular block that caught my eye is the slider element: <div id="sliderDispo" class="slider slider-dispo" data-slider-init="" data-slider-color="#0077b5 #EC6E31 #E40B0B" data-slider-step="33" > <div class="slider__interval" ...

Editing the object retrieved from JSON is not possible once it has been fetched

Project. Input text in the field and it appears on the shirt. When you click "see back," there is an issue where new text overlaps old text. Clicking on "see front" allows you to enter new text, with the previous text saved underneath. Question: How can ...

Tips for managing the submission process for dynamically generated formsORStrategies for

<tr> <form role="form" class="manualImportSubmit" action="http://localhost:5000/XXX" method="post"> <td><input name="yyy" value="FormAValue" type="hidden">TestA</td> <td><input name="before_year" class="fo ...

In Chrome, it seems like every alternate ajax request is dragging on for ten times longer than usual

I've been running into an issue with sending multiple http requests using JavaScript. In Chrome, the first request consistently takes around 30ms while the second request jumps up to 300ms. From then on, subsequent requests alternate between these two ...

Incorporate Jquery Append and Each functions into Class addition

I've encountered an issue while trying to retrieve information in JSON format and add an ID to each element. Despite my efforts, my code is not functioning as intended. Although the appending process is successful and I can see all my results in JSON ...

Unable to access the POST value in the current context

I am having trouble retrieving the values from a simple form that consists of two files: APP.js and FORM.ejs. I am attempting to get the values submitted through the form. APP.js: const http = require('http'); const express = require("express"); ...

Incorporate adjustable div heights for dynamically toggling classes on various DOM elements

One of the challenges in developing a chat widget is creating an editable div for users to input text. In order to maintain the design integrity, the box needs to be fixed to the bottom. An essential requirement is to have javascript detect resizing as us ...

Generate a new object from the contents of a div

Having the HTML structure below: <div id="main"> <div id="myDiv1"> <ul> <li>Abc</li> <li>Def</li> </ul> </div> <div id="myDiv2"> <ul> <li>Ghi</l ...

Istanbul provides me with a thorough analysis, yet it always seems to conclude with an error

Currently, I am experimenting with a basic application (found in the Mocha tutorial code available at ) to troubleshoot why Istanbul is giving me trouble. The issue is that Istanbul successfully generates a coverage summary but then throws an error for unk ...

Tips for increasing the height of a popover when clicked

When a user focuses on the password input, a popover displays information. At the bottom of the popover, there is a link. How can I make the popover expand when the user clicks on this link? I have tried adding an !important class for the height value, us ...

Name or Title of a Polygon/Polyhedron Using Three.js

My page contains a sample code that successfully retrieves the name of an object when a user clicks on it. However, the code works well with cubes and spheres but fails with polygons. To see how the clicks respond, you can check the console logs. What shou ...

Determine the presence of a JSON object within a file using JavaScript

Currently, I am developing a mobile app using react-native and have been facing challenges implementing error checking. To store data retrieved from an API in JSON format, I am employing redux along with thunk. At times, the search results yield a JSON res ...

Redirecting users from one page to another using Javascript along with

I am currently working on a project that employs the use of a PHP <? header('Location: <a href="http://url.com" rel="nofollow">http://url.com</a>'); ?> for handling redirects. I find this method particularly effective because of ...