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

What sets Import apart from require in TypeScript?

I've been grappling with the nuances between import and require when it comes to using classes/modules from other files. The confusion arises when I try to use require('./config.json') and it works, but import config from './config.json ...

Traversing through JSON main sections, checking for operation and subsequently retrieving data

I have a json structure below: { users: [ { action: 'add', payload: [Array] } ], categories: [ { action: 'add', payload: [Array] } ], products: [ { action: 'add', payload: [Array] } ] } Can you suggest a method using .m ...

``What is the best way to create a v-toolbar with a multiline title in Vue.js

In my Vue.js app with Vuetify library, I am facing an issue with displaying v-cards titles of varying lengths. The problem is that the title breaks off and shows "...", instead of wrapping to multiple lines as needed. How can I change this? Template: < ...

Limiting the number of characters in a textarea using React with TypeScript

Having encountered two issues, I've developed a textarea component that not only allows users to input text but also keeps track of the number of characters they have typed. First Issue: I'm attempting to check if the length of the current input ...

There seems to be an issue with the post request to a PHP file as it is returning a null value when

I have been struggling with this issue for a while now and can't seem to understand why I keep getting null after calling my $.ajax function. I pass an associative array containing the method name, then invoke the method in PHP to return a JSON string ...

Adjusting the options in the subsequent dropdown menu based on the selection made in the initial dropdown menu

I am currently working on select boxes where values are dynamically added through an array. For example, if I have 4 values in the first select box, I only want to display 3 values in the second select box, excluding the value that has already been selecte ...

Ways to pass data to a different module component by utilizing BehaviourSubject

In multiple projects, I have used a particular approach to pass data from one component to another. However, in my current project, I am facing an issue with passing data from a parent component (in AppModule) to a sidebar component (in CoreModule) upon dr ...

I'm curious about the process by which custom hooks retrieve data and the detailed pathway that custom hooks follow

//using Input HOOK I am curious to understand how this custom hook operates. import { useState } from "react"; export default initialValue => { const [value, setValue] = useState(initialValue); return { value, onChange: event =&g ...

Is there a way to efficiently include numerous jQuery scripts in a batch process, each with a slight variation, using a loop?

Currently, I have a script that calculates the blur effect for multiple images based on the mouse position and scroll position. However, I am looking for a more efficient way to apply this to around 100 images without duplicating the script each time. var ...

Is there a way to interact with a DOM element through clicking and then pass it as a variable using PHP?

Is there a way to configure a table so that data from a specific row is sent to a PHP script and displayed in a section on the website when the user clicks on that row? I am looking to pre-fill a data entry form with information from a selected row, allow ...

The function `React.on('languageChanged')` is not effectively detecting changes in the language

I'm new to working with React and I'm looking for the best way to detect when a user changes their language preference. I am currently using next-translate to handle translations, but for some resources that come from an API, I need to update the ...

Is there a mechanism in Vuefity that triggers an event when the number of items per page is switched? :switch-items-per-page-trigger

My tables have been customized with the following settings: :items-per-page="itemsPerPage" :footer-props="{ 'items-per-page-options': [10, 20, 30, 40, 50, -1] }" The itemsPerPage values are sourced from the user's pr ...

Angular calls a factory method from within its own factory

When working in my controller, I encountered a situation where I needed to call a factory function recursively. Previously, the code worked fine as simple JavaScript functions not defined within the factory itself, but I wanted to improve isolation. Here ...

How can I align the isometric camera in THREE.js to the center of a cube?

Hey there, I'm working on a tricky exercise involving setting up a camera and cube with THREE.js. The goal is to maintain the cube's initial ratio while ensuring the camera is focused on the center of the cube. Although I believe I've succes ...

The ID data from my axios.delete request is not properly transferring to the req.body, causing issues with deleting from mySQL

Currently, I am utilizing Axios to manage the requests in my application. Upon testing with PostMan, it has been confirmed that my DELETE request is functioning properly. However, when implementing the code for the front end, I encountered a 404 error duri ...

Any tips on properly testing a custom Vue component with custom input functionalities?

While browsing through the Vue.js documentation, I came across an interesting example of a custom input component. I am currently exploring how to create a unit test for a similar component. The usage of the component is illustrated like this: <currency ...

Tips for sending a PHP JSON array to a JavaScript function using the onclick event

I am trying to pass a PHP JSON array into a JavaScript function when an onclick event occurs. Here is the structure of the PHP array before being encoded as JSON: Array ( [group_id] => 307378872724184 [cir_id] => 221 ) After encoding the a ...

Is there a way to run only one instance of puppeteer.launch() and simply forward pages to it in Node.js?

I have a concern regarding the code snippet below. It appears to be launching the browser on every request, potentially causing server issues on Heroku. I would like to modify it so that puppeteer is launched as a Singleton instance, where it only needs ...

Is there a way to circumvent the eg header along with its contents and HTML code using JavaScript?

I have a script in JavaScript that is designed to replace the content of data-src attribute within each img tag with src. However, I am facing an issue where this script interferes with the functionality of a slider located in the header section. The sli ...

Transferring data from Node.js server to React client with axios communication

I have a project in the works that involves tracking chefs and their new recipes. I am developing a simple frontend application where users can input a chef's username, which will then be sent to the backend for scraping several cooking websites to re ...