[Vuejs]-Duplicate code – Very similar UI but some of the components and methods are different – Vue

2πŸ‘

Create a reusable component that consists of the Template and styles. Then use it on other components.

Supposed.

ReusableComponent.vue

    <template>
       <div> This is a Reusable component </div>
    </template>
    
    <script>
      export default {};
    </script>
    
    <style>
      ...
    </style>

ComponentA.vue

    <template>
       <ReusableComponent />
    </template>
    
    <script>
      import ReusableComponent from './ReusableComponent';
    
      export default {
        components: {
          ReusableComponent,
        },
        methods: {
           methodJustforComponentA() {
             ...
           },
           ...
        }
      };
    </script>

ComponentB.vue

    <template>
       <ReusableComponent />
    </template>
    
    <script>
      import ReusableComponent from './ReusableComponent';
    
      export default {
        components: {
          ReusableComponent,
        },
        methods: {
           anotherMethodJustforComponentB() {
             ...
           },
           someOtherMethods() {
             ...
           },
           ...
        }
      };
    </script>
πŸ‘€Olie Cape

1πŸ‘

Typical Create and Update in Vue/React is handled as follows. It is based on the assumption that your UI remains same during create and update workflows. What changes is the API and Authorization logic.

Step 1

Create a dumb MyForm component which has only static form controls that. In terms of props the component would have following props:

// Value of some type T that you receive from parent component to render
// @input event raised by `MyForm` for any changes done by user to the form
value: T;
@input: (newValue: T) => void;

Step 2

Create two higher order components, NewEntity and EditEntity. These two components are responsible for making API calls and getting the data. Further these components would then pass this data as prop to MyForm component.

These components would also be the leaf components i.e. the components connected to the client-side router endpoints.

Step 3

If you have some common behavior (Not UI – already extracted into MyForm. It is about behaviors like computation, APIs for autocomplete, suggestions, etc.), then you can use Mixins or Extend components using classes to further extract out the common code. With Vue 3, prefer to use composition API over Mixins for this.

πŸ‘€Harshal Patil

Leave a comment