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

Occasionally, the system may mistakenly flag a password as invalid even though it is indeed correct

To ensure the password meets certain criteria, it must start with a Z, have at least 8 characters, and contain an asterisk *. Take a look at this validating function: function validatePassword() { var strPassword; //Prompt user to enter pas ...

Is it possible to redirect any web traffic using an authentication script?

Scenario: I'm currently working on a social networking project and I'm looking for a way to validate every redirect or refresh by directing the user through another script before reaching their final destination. I've considered using a &apo ...

A novel way to enhance a class: a decorator that incorporates the “identify” class method, enabling the retrieval

I have been given the task to implement a class decorator that adds an "identify" class method. This method should return the class name along with the information passed in the decorator. Let me provide you with an example: typescript @identity(' ...

Clicking on a button will allow me to select only a portion of text within a specific cell of

Inside a table, there is a paragraph of text enclosed in a <td></td> element. Take for example the following passage. Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard ...

Ensure the left and right screen widgets remain fixed in their positions as the user scrolls down the page using the spacebar

Currently, I have a webpage that showcases products with a large height attribute. I am looking for a way to make the page scroll down when the user hits the space bar to view more products. However, I want my screen widgets such as the shopping cart and ...

What is the best way to display the current scroll percentage value?

I'm trying to update this code snippet import React from 'react' const App = () => { function getScrollPercent() { var h = document.documentElement, b = document.body, st = 'scrollTop', sh = 'scrollHeight ...

Cleaning up React async functions using hooks for fetching data

This code snippet is from a functional component. Within this component, there is a submit() function that handles form submission: async function handleSubmit(event) { event.preventDefault(); try { let resp = await fetch("FOOBAR/BAX", { ...

Different ways to rearrange the placement of Export buttons in a personalized div or outside the table using Datatable

I would like to display the export buttons outside of the table. While searching on stackoverflow, I came across an example that uses the Select options method. You can find the example here. If anyone knows how to achieve this, please modify it and shar ...

What is the best method to transfer text entered in one textarea to the output of another?

I recently picked up JavaScript again and encountered an issue while developing an app. I am struggling to pass input from one textarea to another, where the text should be converted to uppercase. I attempted to tweak code from w3, but I prefer to achieve ...

Spin the text inside an <li> element generated by JavaScript

I am currently working on a unique script designed to create a custom number of slices for a circle. The items in the circle are being displayed as shown in this generated circle image. This is the Javascript code I have been using: for () { men ...

When $(.class) displays result, Javascript ceases execution

In the code snippet below, I am trying to load a group of products from a category when the user clicks on the .expandproducts button: $('.expandproducts').click(function(){ id = $(this).attr("data-id"); urlajax = document.location.origi ...

Is there a way to dynamically update one input field while another input field is being modified? [HTML / JS]

I have a form with 3 input fields. One of the inputs is disabled, while the other two are enabled. The goal is to combine the values entered in the enabled fields to populate the disabled field. How can this be achieved? Is it possible for the value in th ...

Switch Between More and Less Text - Implement Smooth Transition on Shopify Using Javascript

I recently implemented a More/Less toggle button using resources from this website. The functionality is there, but I now want to add a smooth transition effect. When the user clicks on "read more," I would like the hidden content to gradually appear, and ...

Issues with injection of angularjs, sockjs, and angular-sockjs are causing functionality to not

As a newcomer to technologies like angular, sockjs-client, and cyclone, I've encountered an injection issue while attempting to utilize a component created by bendrucker. The component in question can be found at this link: https://github.com/bendruck ...

NumericError on /post_create/ unrecognizable numeric value: 'manish'

I have a unique vision: I want to create posts with different authors in separate models def post_creation(request): author, initiated = Author.objects.get_or_create(name=request.user.username) form = CreationForm(request.POST or None , request.FILES or ...

The Angular Node server is responding with the error message "You have entered 'undefined' instead of a stream."

Using angular 9 + universal has been smooth sailing until I encountered an issue after building the app with npm run build:ssr and attempting to run it using node: node dist/app/server/main.js. The error message that popped up in the terminal was: Node ...

Using Jquery & HTML5 for Seamless Transition between Portrait and Landscape Modes

I am working on making my HTML page more user-friendly for tablets. One issue I'm facing is that when the tablet's orientation changes, the menu doesn't hide correctly if the width is less than the height. Here is the code snippet I have so ...

Integrating a personalized dropdown feature into the Froala editor within an AngularJS environment

After searching for a JavaScript rich text editor that doesn't use frames and allows easy customization of the toolbar with custom dropdowns, I came across the Froala editor. It also offers AngularJS-friendly directives. Previously, I tried using Text ...

Why won't the CSS update in Next.js when the local state variable changes on page load?

I seem to be facing an issue with a variable stored in localStorage that changes when using a toggle button. The color changes correctly upon toggling the button, but upon page refresh, it doesn't display the correct color saved in local storage. Eve ...

Manipulating state in React

Currently, I am enrolled in Samer Buna's Lynda course titled "Full-Stack JavaScript Development: MongoDB, Node and React." While working on the "Naming Contests" application, I encountered a piece of code within the App component that has left me puzz ...