Componentizing Vue for Better Reusability

Currently tackling a large application filled with legacy code, I'm facing a repetitive issue that has popped up twice already. It's becoming clear to me that there must be a more efficient way to solve this problem. Here's what I'm dealing with.

There are three distinct pages within the app where I need to introduce similar Vue functionality. However, the challenge lies in the fact that these pages have vastly different HTML/Blade templates. As a result, it feels like I have to provide separate HTML/Blade templates to the component alongside the component props.

To navigate this dilemma, I've managed to utilize Vue inline-templates that effectively address the varying HTML/Blade template issue.

Nevertheless, an ongoing concern persists - I currently have three individual .js Vue components, each corresponding to a specific page. Although functional, the Vue code within these files shares striking similarities.

In addition, there's a possibility that down the line I'll need to incorporate more distinctive Vue code into each component, and I want to keep that option open.

My goal is to discover a method to reuse the largely similar Vue code across all components. While I've toyed with the idea of nesting the same child component inside these three separate components, the differences in their HTML/Blade structure seem to present an obstacle.

If you have any suggestions on how to tackle this conundrum, I would greatly appreciate your input. The last thing I want is to end up duplicating an excessive amount of Vue code!

Answer №1

Hats off to user gratefuluser for sharing the solution in the comments above. Utilizing mixins turned out to be the perfect approach for my situation. Instead of the initial setup shown below:

Vue.component('first-component', {
    template: // a unique content
    methods : {
        functionNumber1: function () {
            // perform an action
        },
});

Vue.component('second-component', {
    template: // completely different content
    methods : {
        functionNumber1: function () {
            // do the same action
        },
    }

});

The revised code simplifies everything as follows:

const myMixin = {
    methods : {
        functionNumber1: function () {
            // do the same action
        },
}

Vue.component('first-component', {
    template: // a unique content
    mixins: ['myMixin']
});

Vue.component('second-component', {
    template: // completely different content
    mixins: ['myMixin']
});

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

Enliven the character limit reaction by incorporating a thrilling shake animation when it reaches

I have implemented a feature in my component where if a user reaches the character limit, the component should shake. However, despite my efforts, the shaking effect is not working in the current code. const useStyles = makeStyles(() => ({ shake ...

Exploring the capabilities of multiple nested controllers in AngularJS

I am facing a challenge that I haven't been able to find a solution for online. My search form includes multiple instances of a common controller used for typeahead/autocomplete searches. Each controller is set up with different parameters for search ...

Signing in using Passport.js with mongoDB authentication

Apologies if this question appears redundant, but I am struggling to resolve an issue with a "MISSING CREDENTIALS" error when trying to implement user login using email and password. Despite going through numerous responses, none have provided a solution. ...

How to use Javascript to set focus on a dropdown list within a PHP script

Having trouble setting focus on the dropdown list in my PHP page dc-test.php, where there are two dropdown lists that are interdependent. The values for these dropdown lists are fetched from a database table. I am unable to set focus on the first dropdown ...

Why won't console.log function execute in this particular situation?

(function( $ ){ $.fn.openlayers = function( mapElementId, options ) { alert(console.log); console.log(options); ... } }); While attempting to enhance the capabilities of a JavaScript library, I encountered an unexpected issue. ...

Laravel modal form submission with verification

Recently, I started working with laravel and I'm struggling to manage laravel, ajax, and jquery. Currently, I am trying to insert data into the database. I have succeeded in doing so, but I encountered an issue with data validation. I want to validate ...

Troubleshooting Challenges in JavaScript/jQuery Hangman Game

Having trouble with my hangman game's game loop. Attempting to replace correct letters as the game runs through the word, but it's currently: looping through the word checking if the guessed letter is in the word returns index[0] Tried splitti ...

Associate an alternate attribute that is not displayed in the HTML component

Imagine there is a collection of objects like - var options = [{ id: "1", name: "option1" }, { id: "2", name: "option2" } ]; The following code snippet is used to search through the list of options and assign the selected option to anot ...

An issue arises when using JSON.parse() with regular expression values

I am encountering an issue with parsing a JSON string encoded with PHP 5.2 json_encode(). Here is the JSON string: {"foo":"\\."} Although this JSON string is valid according to jsonlint.com, when using the native JSON.parse() method in Chrome a ...

Learn the process of encoding a string in JavaScript or jQuery and then decoding it with PHP

I am facing an issue with updating a field in the database using Ajax and PHP. Everything runs smoothly except when there are special characters present, like this: اللهم اني اشكو اليك ضعف قوتي وقلة حيلتي وهواني عل ...

Display words on screen and then alter hue using HTML and CSS

Is there a way to dynamically change the color of text inside <a> tags from black to red after a specific time interval and keep it permanently red? do { document.getElementById("code").innerHTML +="<a>Hello World</a><br>"; awa ...

Issue with Jquery modal not functioning properly on second attempt

Currently, I am working on developing an application using CodeIgniter. However, I have encountered a problem where the modal window does not open for the second time. Here is a more detailed explanation of the issue: The form (view) in question contains ...

Looking to implement pyperclip functionality on Heroku platform

Is it feasible to utilize pyperclip on Heroku with a Selenium application in order to copy something to the clipboard? Since the platform utilizes a 'headless' browser and lacks a GUI, accessing the clipboard is challenging. Is there any way for ...

Unable to interpret the JSON reply from the server

I am currently developing a web application that sends data to a website, which then updates its database and returns a JSON array to replace my web app page. I am using AJAX for this query, but I am facing an issue with preventing the overwriting of my we ...

Setting up an SSL certificate for an Express application: A step-by-step guide

I am currently trying to set up my Express server in order to pass the SSL certificate and transition from http to https. After going through the Express documentation, I still haven't been able to find a suitable solution. While some suggestions lik ...

Getting a JSON response from a JSP page through an AJAX request

I'm encountering an issue with a JSP page that is supposed to send a JSON response when requested through an AJAX call. However, the response is being directed to the error part of the AJAX call instead of the success part. Below is the code in my JS ...

Laravel:MySQL Error - The database is unable to add or update a child row due to a foreign key constraint violation (error code: 1452)

I am having trouble applying a foreign key to the user_id column, connecting it with the ID column of the users table. Despite attempting to set this up through migrations and in workbench, I keep encountering the following error: Integrity constraint ...

What is the best way to connect objects that have been separated?

Looking for a way to reattach my detached objects and wondering how to replace the function that currently only triggers an alert. Any suggestions or help is appreciated. http://jsfiddle.net/jy2Zj/ In addition, I have another question - is there a method ...

Encircling a particular group of cells with a border

I have completed the component with a table layout. My current challenge is figuring out how to surround a range of selected cells with a border, similar to the first cell in the group shown below: https://i.stack.imgur.com/5Euht.png I attempted using d ...

Execute tests on changing files using cypress.io

I'm currently experimenting with using Cypress to test a large Angular application that I've developed. What I want to achieve is to load an expectation file into my test and then run the test based on this expectation file. Despite trying diffe ...