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

Processing hover attributes in Tailwind-styled-components

I'm currently working on a website that features a dark mode, and I want to utilize the dark prop in tailwind-styled-components. The props work fine in all instances except for actions like hover, active, focus, etc. When attempting to use hover and t ...

Obtain a report using a variety of different conditions

My database has a table with the following fields: TPI CLICKS IMPRESSION CLASSIFY I am looking to retrieve 3 specific results: 1) Calculate SUM(CLICKS)/SUM(IMPRESSION) * 100 GROUPED BY TPI 2) Calculate SUM(IMPRESSION) WHERE CLASSIFY = "XYZ" GROUPED BY ...

The XMLHttpRequest onload() function is failing to pass an instance of the XMLHttpRequest object

I am facing an issue with a function that sends a basic AJAX request to my server. The JavaScript code in the browser is as follows: function testRequest() { var xhr = new XMLHttpRequest(); xhr.onload = () => { console.log("RESPONSE R ...

Using jQuery, effortlessly scroll a div to a specific vertical position of your choice

After referring to this previous question: Scrollpane on the bottom, css is hacky, javascript is hard I followed the same scrolling method as explained in the accepted answer. Now there's a new requirement to select a specific item (e.g., through a ...

Trying to work through solving the issue of accessing document.frames["someframe"].function in Chrome instead of IE

I am encountering an issue with my code that is working in Internet Explorer but not in Chrome. try { top.document.frames["myFrame"].compare(); } catch(err) { alert("This is not executed."); } Any suggestions on how to resolve this compatibility pr ...

What is the best way to link this interval service with a view component?

Exploring the AngularJS documentation for $interval, I came across an interesting example demonstrating how to utilize $interval in a controller to create a user-friendly timer in a view. The official example code can be found on the angularJS documentatio ...

Integrating JSON with the DOM

Currently, I am searching for a library that offers a simple method to bind JSON data to existing DOM elements that have been generated by a Rails view template. The main reason behind this requirement is that my application features in-place editing (uti ...

Solving Mixed Content Issues in JavaScript

I'm attempting to retrieve information from OMDB API, but I'm encountering an issue with mixed content images. OMDB pulls its data from IMDB, which does not allow the use of https images. Therefore, all image sources must be prefixed with http. ...

Modify mesh in three.js scene

Is there a way to dynamically change a mesh in a group triggered by a button click? I am loading an external .obj file: loader.load( obj, function ( object ) { createScene( object, mod.tipo, pid, cor.replace("#","0x") ); }); and adding it to a gro ...

jQuery mobile enhancing user experience with dynamic background images

I am having trouble setting different background images for each page in jQuery Mobile. <div data-role="page" id="pageone">... </div> <div data-role="page" id="pagetwo">... </div> Since each page has a unique ID, I tried ...

I am encountering an issue with vue-router where I am finding it difficult to exclude certain words from the path regex

Currently facing an issue with vue-router where I need to exclude certain words such as: word1, some-word2, word3... from the router path { path: '/:pageIdenfifier(?!word1|some-word2|word3), name: 'SomePage', component: () =&g ...

Tips for handling notifications that have been read and unread in a React application

In my current project using React JS, I am tasked with creating a notifications component that will display account-related activities. The notifications need to be sorted into read and unread categories. My main question is how should I manage the read a ...

Exploring the method of retrieving nested JSON objects in Angular

When my API sends back a JSON response, my Angular application is able to capture it using an Interface. The structure of the JSON response appears as follows: { "release_date":"2012-03-14", "genre_relation": ...

After the installation of Windows 10 and the latest version of NodeJS, Gatsby seems to be

The gatsby project I set up following the official website instructions seems to be malfunctioning. NodeJS version: v16.15.0, npm version: 8.8.0, gatsby version: 4.13.0, gatsby CLI version: 4.13.0 C:\Users\Dell\Desktop\New folder&bsol ...

Use jQuery's .each method to reiterate through only the initial 5 elements

Is there a way to loop through just the initial 5 elements using jQuery's each method? $(".kltat").each(function() { // Restrict this to only the first five elements of the .kltat class } ...

Issue with locating index.html when setting up Ionic Vue 3 on a subdomain hosted on Firebase

After successfully developing an app with Ionic and Vue 3, I decided to transfer the same functionality to my website's portal subdomain using the existing code. Additionally, I have another subdomain (www) that points to a separate HTML-only site wit ...

Vue: Preventing component from re-rendering upon routing again

I'm experiencing an issue with Vue behavior that I can't quite grasp. My situation involves routing between components. methods: { redirectToLogin() { this.$router.push("/login"); }, redirectToRegister() { ...

React.js Component Composition Problem

I am attempting to replicate the following straightforward HTML code within a React environment: Traditional HTML <div> Hello <div>child</div> <div>child</div> <div>child</div> </div> React(working ...

What is the process of setting up various initialization parameters for a DataTable?

Here is a snippet of JavaScript code I have been using to initialize a DataTable: $(document).ready(function() { $('#example').DataTable( { dom: 'Bfrtip', buttons: [ 'copyHtml5', &a ...

Error in Angular: Unexpected '<' token

After setting up my angular and express app using the angular-cli and express command lines, I successfully built the angular app with the ng build command. However, when attempting to serve it with the express server, I encountered the following error in ...