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

Combining DataTables with multiple tables sourced from various JSON arrays

I am trying to display data from two different arrays within the same JSON source in two separate tables, but my code seems to be malfunctioning. JSON Information: { "Policies": [ { "name": "A", "id": "1", "score": "0" } ], ...

Trouble encountered while attempting to choose a single checkbox from within a v-for loop in Vue.js?

<div id="example-1"> <ul> <input type="text" v-model="searchString" placeholder="Filter" /> <p>sortKey = {{sortKey}}</p> <li v-for="item in sortedItems"> <input class="checkbox-align" type="checkbo ...

Steps to fix issues with Cross-Origin Read Blocking (CORB) preventing cross-origin responses and Cross Origin errors

var bodyFormData = new FormData(); bodyFormData.set("data", "C://Users//harshit.tDownloads\\weather.csv"); bodyFormData.set("type", "text-intent"); //axios.post("https://api.einstein.ai/v2/language/datasets/upload", axio ...

Exploring intricate designs using HTML and Javascript

After extensive experience with both WPF and HTML5 JavaScript, one thing that stands out to me is the clear organization provided by XAML's defined panels. Grid, StackPanel, DockPanel, WrapPanel, and others offer a straightforward way to achieve consi ...

Utilizing Angular routing in HTML5 mode within a Node.js environment

While I've come across other solutions to this problem, they all seem to have drawbacks. One option leads to a redirect, which could be disastrous for my front-end application that relies on Mixpanel. A double-load of Mixpanel results in a Maximum Ca ...

Creative jQuery hover effects tailored to the size of the viewport

Currently expanding my knowledge of jQuery and encountering an issue with some code. I am trying to incorporate an animation effect (fadeIn/fadeOut) when the user hovers over a specific element. However, if the viewport is resized to below 480px for mobil ...

Is it possible to center the image and resize it even when the window is resized?

My goal is to position an image in the center of the screen by performing some calculations. I've tried using: var wh = jQuery(window).innerHeight(); var ww = jQuery(window).innerWidth(); var fh = jQuery('.drop').innerHeight(); var fw = jQ ...

Hiding content in HTML with the Display:none property

After exploring various posts on this topic, I am still unable to find a solution that fits my specific scenario. Despite the challenges, I thought it would be worth asking for recommendations. Currently, I have a PowerShell script generating a report in ...

Experiencing a problem with Datatables where all columns are being grouped together in a single row

After creating a table with one row using colspan and adding my data to the next row, I encountered an issue with the datatables library. An error message appeared in the console: Uncaught TypeError: Cannot set property '_DT_CellIndex' of unde ...

Is there a way to set up an automatic pop-up for this?

Experience this code function AutoPopup() { setTimeout(function () { document.getElementById('ac-wrapper').style.display = "block"; }, 5000); } #ac-wrapper { position: fixed; top: 0; left: 0; width: 100%; height: 100%; back ...

Trying to dynamically filter table cells in real time using HTML and jQuery

During my search on Stack Overflow, I successfully implemented a real-time row filtering feature. However, I now require more specificity in my filtering process. Currently, the code I am using is as follows: HTML: <input type="text" id="search" place ...

Data is not appearing as expected in the React component when using the data

I'm currently facing an issue while working with MUI. I am able to retrieve the list in console.log, but nothing is being displayed on the screen - no errors or data, just the console.log output. Here is a snippet of the data that I am receiving: ...

Encountering the issue "Error: _LoginPage.default is not a constructor"

This is the code I wrote: /// \<reference types = "cypress" /\> class LoginPage { visit() { cy.visit("https://ec2-35-179-99-242.eu-west-2.compute.amazonaws.com:2021/") } username(name) ...

Is there a way for me to prevent the setTimeout function from executing?

I have a function that checks the status of a JSON file every 8 seconds using setTimeout. Once the status changes to 'success', I want to stop calling the function. Can someone please help me figure out how to do this? I think it involves clearTi ...

Ways to conceal the 'Return to Top' button in a script that is only revealed after navigating to the bottom of the page

Can anyone help me hide the 'Back to Top' button in a script that only appears after scrolling to the bottom of the page? I need to take screenshots without it showing up. I've tried using the code below, but the 'Back to Top' but ...

Replicate the functionality of a backend API using AngularJS

Currently, I am in the midst of creating a GUI for an application that is still undergoing API development. Although I have a vision of how it will look, it lacks functionality as of now. Hence, I need to replicate its behavior until the API is fully funct ...

A method to find the sum of the final n elements in an array by employing Arr.reduceRight

I have successfully calculated the sum of the last n elements in an array using a for loop. Is it possible to achieve the same result using Arr.reduceRight instead? x = [1,2,3,4,5]; y = 0 for(let i=x.length; i>x.length-3; i--) { console.log(x[i-1]); ...

Hybrid application: Manipulate HTTP user agent header using AngularJS

I am currently developing a hybrid app using Cordova and Ionic. My current challenge involves making an HTTP request to access a server where I need to modify the user agent of the device in order to pass a secret key. $http({ method: 'GET&a ...

Troubleshooting problem with sorting in Angular 4 material header

Using Angular 4 material for a table has presented me with two issues: 1. When sorting a table, it displays the description of the sorting order in the header. I would like to remove this. It displays "Sorted by ascending order" here. The ngx modal theme ...

Tips for altering the color of a specific bar in the Material UI BarChart component

I have implemented the following code to generate a Graph: const namesArray = Object.values(tableData).map(item => item.name); const valuesArray = Object.values(tableData).map(item => item.value); return ( <Box> <SimpleCard ti ...