Improving functions in vue.js

Currently working on my personal project, which is an HTML website containing tables generated through vue.js. I believe that my code could be simplified by refactoring it, but I am unsure about where and what changes to make. Below is the section of the code where I am facing challenges:

var players = [
    { ID: 1, NAME: "Chandler Bing", TEL: '305-917-1301', rank: '3 dan' }
];
var criteria = ["ID", "NAME", "TEL", "rank"];
let crit = [
    {
        name: "ID",
        show: true
    },
    {
        name: "NAME",
        show: true
    },
    {
        name: "TEL",
        show: false
    },
    {
        name: "rank",
        show: true
    }
]
const Standings = {
    template: `<div v-cloak id="editable" style="background-color:#adb8ff">
    <div id="form">
      <!-- Code truncated for brevity -->
    </table>
</div>`,
    props: [],
    methods: {
        /* Methods content removed for brevity */
    },
    data: function() {
        return {
        pname: "",
        rank: "",
        rows: players,
        columns: activeCriteria
    }
    }

}
const Pairings = {
    template: `<div v-cloak id="editable" style="background-color:#aaabca">
    <table class="fixed" id="tournament">
     <!-- Content omitted for conciseness -->
 </table>
 </div>`
}
/* Remaining code snippets retained as-is */

I have realized that I'm duplicating the same methods in both Standings and editable components. This redundancy is necessary for the code to function properly, but I suspect there might be a more efficient way to handle these shared methods. I'm open to suggestions and corrections regarding this observation.

Answer №1

If you want to organize your functions, you can create a .js file specifically for them:

YourFunctions.js

export const playerSubmit = () => {
            players.push({
                ID: i,
                NAME: this.pname,
                TEL: "placeholder",
                rank: this.rank + " " + document.getElementById("rankT").value
            });
            i++
            this.pname = "";
            this.rank = "";
            return false;
        };
export const addRound = () => {
            var pushActive = {};
            var counterT = counter.toString();
            players.forEach(p => p[counter] = "");
            pushActive = { name: counterT, show: true };
            activeCriteria.push(pushActive);
            var found = false;
            found = crit.filter(c => c.name == counterT).length > 0;

            if (!found) {
                crit.push(pushActive);

            }
            counter = counter + 1;

            found = false;
        };

export const previousRound = () => {
            var l = crit.length - 1;
            if (counter > 1) {
                crit[l].show = false;
                activeCriteria.pop(activeCriteria[l]);
                counter = counter - 1;
            }

        }

Then in your Vue app, you can import these functions at the top like this:

import { playerSubmit, addRound, previousRound}  from './YourFunctions.js';

Now you can use them within your app as needed.

For additional information, you can refer to: https://forum.vuejs.org/t/how-to-use-helper-functions-for-imported-modules-in-vuejs-vue-template/6266/2

VueJS accessing externaly imported method in vue component

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

What is the correct way to add a library to webpack configuration?

Currently, I am working with Rails 6 and webpack in my project. I am interested in integrating the library jquery-textcomplete, but I am unsure about how to properly include it in the application.js file. Here are the steps I have taken so far: I instal ...

What is the best way to integrate PHP scripts into jQuery?

I need help integrating PHP into my jQuery sample. Specifically, I would like to insert a PHP variable ($sample) into the "var para1" in the code below. var storyIndictor = jQuery(_storyIndictors[position]); var _content = jQ ...

Tips for integrating Material UI with useRef

There seems to be an issue with the code, but I haven't been able to pinpoint exactly what it is. My question is: How do you properly use useRef with Material UI? I am attempting to create a login page. The code was functioning fine with the original ...

Is there a way to escape from an iFrame but only for specific domains?

if (top.location != self.location) { top.location = self.location.href; } If my website is being displayed in an iFrame, this code will break out of it. But I want this to happen only for specific domains. How can I perform that check? ...

Leveraging the power of Map and Sort to display the items containing image URLs alongside their respective timestamps

I'm diving into firebase and utilizing react, and currently I've come across this snippet of code: {photos.map(url => ( <div key={url} style={card}> <img src={url} style={image} /> <div s ...

Angular is encountering an issue where it is unable to read the value of a JavaScript function, despite the object having a value

I have developed some JavaScript functions that involve reading and writing to a JSON file, with the intention of calling them in an Angular environment (from TypeScript code) using the jsonfile library. Below is the code snippet: function savePatient(pa ...

Tips for successfully including a forward slash in a URL query string

My query involves passing a URL in the following format: URL = canada/ontario/shop6 However, when I access this parameter from the query string, it only displays "canada" and discards the rest of the data after the first forward slash. Is there a way to ...

What is the best way to modify the size of a canvas element while maintaining effectiveness?

I've encountered an issue while using Canvas to create a pie chart with chart.js. Despite adjusting the dimensions of the canvas element, it continues to take up the entire page. <canvas id="myChart" height ="200" width="200"></can ...

Creating a Selectable Child Form in ReactJS that Sends Data to Parent Form

Sorry for the lack of details, I'm struggling to explain this situation clearly. I'm currently learning ReactJS and JS. In a project I am working on, I have the following requirements: There is a form where users can input text and numbers. The ...

Restricting the number of lines within a paragraph in Angular 2

Is there a method to limit the number of lines in a <p> tag and add an ellipsis (...) at the end? Using character count for truncation doesn't work well as the width of the element varies according to device screen size. ...

React component is unable to identify prop

I'm attempting to send an array of objects from the main App.js file to a smaller component using props. However, for some reason, the prop is not being recognized within the smaller component file. https://i.stack.imgur.com/WuyFr.png https://i.stac ...

Exiting a void method in JavaScript/Typescript using the return or break statement

I find myself dealing with a complex method in Typescript that contains multiple if else if else constructs. It's a void method, and I'm wondering how I can exit the method based on a specific if condition without having to execute the remaining ...

Tips for customizing the color of Menu in material-ui v5

I've been searching for solutions to change the background color of the Menu, but the methods I found are outdated. The use of @mui/styles and makeStyles is now deprecated, as stated in mui.com/styles/basics/#hook-api. I attempted to change the backgr ...

Node.js encountering req.body as undefined when using form-data as the content-type

After creating a small demonstration for this form-data passing API, I attempted to test it using Postman. However, I encountered an issue where no data was being retrieved. Code const http = require("http"); const express = require("expres ...

What is the best way to combine API calls using rxJs subscribe and map in Angular?

Currently, I am executing multiple API requests. The first one is responsible for creating a User, while the second handles Team creation. Upon creating a User, an essential piece of information called UserId is returned, which is crucial for the Team cre ...

Issue with Angular Factory not being invoked

I am currently using a tutorial to create a MEAN app with Google Maps. However, I have encountered an issue where the map is not appearing on the page. Surprisingly, there are no errors in the browser console and even when debugging with node-inspector, I ...

Extract the year from a string formatted as 1880-01-01T00:00:00.000

Looking to extract the year from an array of dates with format 1880-01-01T00:00:00.000. What's the most efficient method to accomplish this using JavaScript? ...

Invoke a function using the output of a different function

There is a function whose name is stored in the value of another function, and I need to invoke this function using the other one. The function I need to call is popup() random() = 'popup()' if ($.cookie('optin-page')) { } I attemp ...

AngularJS's angular.element is currently accessing the current Document Object Model

While experimenting with angular.element, I was curious about accessing the current DOM from an ng-click event. Is there a way to do this? For example: <div ng-click="angular.element(curElement).parent()..."></div> How can I retrieve the cur ...

Trouble Arising in Showing the "X" Symbol upon Initial Click in Tic-Tac-Toe Match

Description: I'm currently developing a tic-tac-toe game, and I've run into an interesting issue. When I click on any box for the first time, the "X" symbol doesn't show up. However, it works fine after the initial click. Problem Details: ...