Enhancing VueJS2 components by optimizing code structure to eliminate duplicate elements

The following code is used in two different components, so please avoid using props. Utilize data variables and largely similar methods but with different component templates.

<template>
   
</template>

<script>
export default {
    name: "abc",
    data() {
        return {
            address: {
                billing: {
                    address1: [],
                    first_name: "",
                    last_name: "",
                    email: "",
                    phone: "",
                    city: "",
                    postcode: ""
                },
            },
        };
    },
    created() {
    },
    mounted() {
    },
    updated() {
    },
    methods: {
        xyz() {},
    },
};
</script>

What is the best approach to handle this? The vueJs3 Composite API setup() hook provides the optimal solution for this scenario.

However, as I am using Vue.js 2, how can I achieve this without duplicating the declaration of data variables and methods?

One suggested method is to utilize a service class (JavaScript Class).

Service Name: utils.js

For example, use

this.utils.address.billing.address1
, this.utils.xyz(); but I prefer accessing them directly like this.address.billing.address1; and this.xyz();

Answer №1

Utilizing a MIXIN in your project is recommended:

To begin, create a new file named /src/mixins/SomeMixin.js

export default {
data() {
        return {
            address: {
                billing: {
                    address1: [],
                    first_name: "",
                    last_name: "",
                    email: "",
                    phone: "",
                    city: "",
                    postcode: ""
                },
            },
        };
    },
    created() {
    },
    mounted() {
    },
    updated() {
    },
    methods: {
        xyz() {},
    },
}

To implement the mixin in your Component:

<script>
import AddresMixin from "./src/mixins/SomeMixin.js";
export default {
  name: "abc"
  mixins: [SomeMixin],
}
</script>

Your Component will now inherit all data, computed properties, and functions defined within the mixin!

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

AngularJS text area not displaying HTML content

In my Ionic's App, I have a textarea that is used for creating or editing messages. However, I am encountering an issue where the textarea does not render HTML tags when trying to edit a message. I attempted solutions such as setting ng-bind-html and ...

What is the reason for not using constants for events in the Node.js programming language?

Although I am new to node.js, my programming background is extensive. I have noticed that in tutorials and production code, developers tend to use hard-coded strings rather than constants to identify events. To illustrate this point, I randomly selected a ...

Identifying selected shapes in CSS/Javascript by outlining them with small rectangles placed on each corner

Currently, I am working on a University Project that involves creating a selection function for drawn shapes such as rectangles, circles, lines, or triangles. The challenge lies in figuring out the visualization of the selection when a shape is clicked. T ...

What is the method to effectively conduct a testing procedure for JavaScript files that have been exported using

I have a JavaScript file called "sum.js" which contains a simple function: // sum.js function sum(a, b) { return a + b; } export default { sum }; Now I want to write a test for this file using Jest. Here is my "sum.test.js" file in the same folder: // ...

Reading multiple files in NodeJS can be done in a blocking manner, and then the

When retrieving a route, my aim is to gather all the necessary json files from a directory. The task at hand involves consolidating these json files into a single json object, where the key corresponds to the file name and the value represents the content ...

What is the process for transferring a file uploaded from a Vue front end to a Laravel controller?

I'm facing an issue with passing file data from a Vue file upload form to a Laravel controller. Although the data is successfully passed from the page to the store in Vue, I'm unable to access it in my controller: Vue page: update() { this.$st ...

What is the best way to refresh an Angular scope variable with data obtained from the Google Maps Places API?

I am looking to implement a feature where users can search for locations using the Google Places API. When they click on a specific location, I want to update a parameter value in the scope. Here is a visual representation: The Google integration works s ...

What could be causing my code to fail in the useEffect hook every time I make updates to my JSON

I have a function that receives JSON data from the server. Using the {jsonData.map((element) => renderComponents(element, jsonData))} function, I loop through the data and send each object to the renderComponents function along with the full JSON data. ...

Transferring data files through an ajax-based form submission

I am encountering an issue when trying to send a file to a server using AJAX for submission. Despite attempting various methods involving var xhr = new XMLHttpRequest(); and $.ajax({});, I consistently receive the error message Uncaught TypeError: Illegal ...

Next.js appending [object%20Object] to the URL's endpoint

I encountered an error when launching my next app using "npm run dev". The error occurred during the pre-render attempt: GET http://localhost:3000/aave/fundamentals/economics/[object Object] [HTTP/1.1 404 Not Found 434ms] The issue is not specific to thi ...

Guide to crafting a custom asynchronous function in a separate file using Express JS

I have a specific function that I want to create called: my_function.js: module.exports = function(req, res, next){ var js_obj; // Do something with the JavaScript object above // Afterwards, I want to append "js_object" to the request object: req.js ...

The server is unable to process the request with parameters for the specified URL

I've been encountering an error every time I try to post something. articlesRouter.post('articles/:target', async (req, res) => { const target = req.params.target.replaceAll("_", " ") const article = await Arti ...

TABULAOTR, The complete table calculation is failing to be retrieved

Apologies for any language mistakes, as I am Russian :)I am using Tabulator but facing an issue where the table footer is not being printed. I am also unable to retrieve data from the footer. The footer simply doesn't show up and I'm unsure of wh ...

Best way to pass a variable from an html form to a php function using ajax

I am currently developing a voting system for multiple uploads where each uploaded image is within a foreach statement. Each image has a form attached to it with three buttons to vote up, down, or not at all. These buttons are associated with an INT value ...

Error Occurred: Angular View Not Loading

I created a new file named new.html to test navigation, but when I load the page View1.html should appear, instead I see a blank page. Below is the content of my new.html: <!DOCTYPE html> <html data-ng-app="demoApp"> <head> ...

Different JavaScript entities with identical attributes (labels)

Even though JavaScript doesn't have tangible objects, I'm struggling to differentiate between them. Let's say we have two objects called Apple and Orange defined as follows: function Apple(){ this.name = "Apple"; } and function Orang ...

Oops! There seems to be a problem with inserting an image using

I am trying to insert multiple images with a loop when clicked. The images are named "0.jpg","1.jpg","2.jpg" etc. To achieve this, I am using an array with all the elements: {name: '1', result: 1, prefecture: "city", photo1: "0.jpg"}, and my l ...

Implementing the ui-tinymce Directive Within a Different Directive

I am attempting to implement the ui-tinymce directive within another directive: angular.module("risevision.widget.common.font-setting", ["ui.tinymce"]) .directive("fontSetting", ["$templateCache", function ($templateCache) { return { restrict: ...

Modifying an array without altering the reference

Perhaps my approach is not quite right, so please provide feedback if necessary! Imagine having an Array that represents some valuable data. var initial = ['x', 'y']; var duplicate = initial; initial.push('z'); console.log(i ...

The Vue Enter/Leave Transition feature may not function as intended when used in conjunction with opacity settings

Vue.js v2.2.1 JSFiddle: https://jsfiddle.net/loop_/59g7w1pa/8/ .fade-enter-active, .fade-leave-active { transition: opacity .5s; } .fade-enter, .fade-leave-to { opacity: 0; } .fade-enter-to, .fade-leave { opacity: 0.5; } ".fade-enter-to, .fade-lea ...