What is the best approach to developing Vue components with unique templates while maintaining the same functionality without duplicating code?

I am working on a project to develop a custom and versatile datatable component. My goal is to be able to adjust the appearance of the datatable on each page, while maintaining consistent functionality. I want to pass data rows into the component and have the flexibility to customize the layout accordingly. However, I am struggling to figure out how to achieve this. Here's an illustration of my dilemma:

For instance, one page may require this template:

<datatable>
    <div v-for="row in rows" class="header" @click="sortBy(row.field)">row.title</div>
    <div v-for="row in rows">row.value</div>
</datatable>

While another page demands a different layout:

<datatable>
    <h1>
        <span v-for="row in rows" @click="sortBy(row.field)">row.title</span>
    </h1>

    <h3 v-for="row in rows">row.value</h3>
</datatable>

I am grappling with a solution to integrate the sortBy function inside the component. Is there a way to make this work seamlessly?

Answer №1

1. Building a New Component

Component Location: ./src/components/dataTableComponent.vue

<template>
    <datatable>

        <div v-if="!withTitles">
            <div v-for="(row, index) in rows" :key="index" class="header" @click="sortBy(row.field)">row.title</div>
            <div v-for="(row, index) in rows" :key="index">row.value</div>
        </div>

        <div v-id="withTitles">
            <h1>
                <span v-for="(row, index) in rows" :key="index" @click="sortBy(row.field)">row.title</span>
            </h1>
            <h3 v-for="(row, index) in rows" :key="index">row.value</h3>
        </div>

    </datatable>
</template>
<script>
export default {
    name: 'dataTableComponent',
    props: ['rows', 'withTitles'],
    data () {
        return {

        }
    },
    methods: {
        sortBy(field){
            //Sorting logic for this.rows
        }
    }
}
</script>

2. Implementing the Component

<template>
    <div>

        <h2>No Titles</h2>
        <dataTableComponent :rows="rows" :withTitles="true">
        
        <h2>With Titles</h2>
        <dataTableComponent :rows="rows">

    </div>
</template>
<script>
import dataTableComponent from 'src/components/dataTableComponent.vue';

export default {
    components: {dataTableComponent},
    data () {
        return {
            rows: ['AAA', 'BBB', 'CCC']
        }
    }
}
</script>

Explore Vue Documentation for Additional Options

Answer №2

One useful tool in Vue is the slot feature, which allows you to customize components. Check out more information about slots here.

datatable.vue

<template>
  <div>
    <slot name="table-slot"></slot>
  </div>
</template>

<script>
  export default {
    name: 'datatable'
  }
</script>

sampleComp1.vue

<template>
  <div>
    <datatable>
        <div slot="table-slot">
            // include your template data here
        </div>
    </datatable>
  </div>
 </template>

 <script>
   import datatable from './datatable.vue';

   export default {
     name: 'sampleComp1',
     data() {
        rows: [] // populate this array with your data
     },
     components: {
        datatable
     },
     methods: {
        sortBy(field) {
            // perform necessary actions here
        }
        
     }
   }
</script>

sampleComp2.vue

<template>
  <div>
    <datatable>
        <div slot="table-slot">
            // include your template data here
        </div>
    </datatable>
  </div>
 </template>

<script>
  import datatable from './datatable.vue';

  export default {
    name: 'sampleComp2',
    data() {
        rows: [] // populate this array with your data
    },
    components: {
        datatable
    },
    methods: {
        sortBy(field) {
            // perform necessary actions here
        }
    }
  }
 </script>

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

Guide to utilizing a shared route function across various routes in express.js

Is there a way to handle the scenario where I need both www.example.com/12345/xxxxx and www.example.com/xxxxx to trigger the same function in my application using Express? app.get('/:someVar/xxxxx', function(req, res) { /* etc */ }); I can acce ...

What is the process for dynamically looping through a table and adding form data to the table?

I am in the process of developing an hour tracking website that utilizes a form and a table. Currently, I have implemented the functionality where the form content gets added to the table upon the first submission. However, I need it to allow users to inp ...

Finding the Determinant of a 4x4 Matrix: A Ray-Tracing Adventure in JavaScript

Currently, I am in the process of developing a raytracer using Javascript/Canvas and following "The Ray Tracer Challenge" by Jamis Buck. Initially, my code successfully computed the determinant of a 3x3 matrix but encountered issues with a 4x4 matrix. As a ...

Having trouble with parsing the .mjs module from Iconify in Vue 3 CLI project that utilizes the Composition API and TypeScript

Issue Update: After modifying the code from if(data.aliases?.[name2] !== void 0) to: if(data.aliases != null && data.aliases[name2] !== void 0) in the iconify .mjs file, I was able to resolve the error. However, this fix needs to be implemented in ...

Angular identifies when a user navigates away from a page

Currently, I am utilizing Angular 1.5 along with ui-router. My goal is to identify when a user exits a route. The code snippet I have at the moment looks like this: $scope.$on("$stateChangeSuccess", function () { if (!$scope.flag) { //... ...

Steps for modifying a cell within a table using a button click

Hello, I am currently working on a project where I want to display a specific div portion when a user clicks on an image icon within a table. However, I am encountering an issue with the JavaScript code as it only shows the div portion in the first row and ...

Tips for utilizing the nth-child selector to exclude hidden divs

I am facing an issue with displaying random blocks in rows. Each time a block falls into a new row, I want it to have a different style. However, when the user clicks on a button to hide certain blocks using display:none, the problem arises because the nth ...

Combining strings in a loop using Javascript

I have a loop hash data stored in a variable called rec. var rec = { }; for (var b = 0; b < 2; b++) { rec['id'+b] = b</p> } Next, I have a piece of JavaScript code that creates a template for a table. var template ='<tab ...

Creating operations in Angular using the Model View Controller (MVC)

What is the procedure for performing an Add operation in MVC using Angular? var addProductModule = angular.module("addProductModule", []); addProductModule.factory("addProductService", ['$http', function ($http) { return { function savePro ...

Spring Boot is having trouble identifying the JavaScript files

I've incorporated Spring Boot in my project and I'm working with a JSP file that looks like this: <%@ include file="common/header.jsp" %> <%@ include file="common/navigation.jsp" %> <div class="container"> ...

Using JavaScript to create a tree structure with hierarchical organization in JSON

Having some trouble converting a nested hierarchical tree from a JSON array. Looking to create a hierarchical tree structure from the provided JSON data. Below is the data: [{ "_id" : "59b65ee33af7a11a3e3486c2", "C_TITLE" : "Sweet and Snacks", ...

Configuring Laravel to operate on a specific port number?

Currently, I am utilizing nodejs, expressjs, and socket.io to trigger events on my web app via a mobile phone connected to the nodejs server. Although the app is primarily built in JavaScript, I have opted to use laravel for data storage within a database ...

Converting a Click Event to a Scheduled Event using JavaScript and AJAX

Currently delving into the world of AJAX & JavaScript, I have a question for the knowledgeable individuals out there. I am curious to know how I can transform the code below from an OnClick event to a timed event. For instance, I would like to refres ...

Using the scrollIntoView() method in VUE.js to center an li element within a component

One of the components I'm working with has multiple list items, and I want to achieve a functionality where clicking on any item will center it inside the component, making it visible in the center of the view. <card-maintenance v-for="m ...

Stop the execution of javascript code based on the screen width

On my website, I have two menus located in different sections of the page. One menu is shown when the screen width is greater than 555px, while the other menu appears when the screen width is less than or equal to 555px. Although the menus are essentially ...

Displaying various Ajax html responses

The function $('.my-button').click(function(e) is designed to display the output of the MySQL query in display.php, presented in HTML format. While it functions correctly, since each button is looped for every post, the script only works for the ...

How to Efficiently Remove Array Elements by Index in Typescript

What is the best way to remove an item by its index using Typescript? For example: let myArray = ['apple', 'banana', 'cherry', 'date']; // How can I delete the item at index 2? ...

Encountering the error 'node' getProperty of undefined while trying to retrieve data from an array stored in my state variable

Hello, I am currently developing an app that retrieves images from Instagram using axios. I have successfully stored the image files in an array named 'posts' within my state. Looping through this array to display each image is not an issue for m ...

Increase the div id using jQuery

I've got this code snippet here and, oh boy, am I a newbie. How can I increase the number in the div using a jQuery script? if($res >= 1){ $i=1; while($row = mysqli_fetch_array($qry)){ echo "<div clas ...

Using TypeScript gives you the ability to specify the type of an object while destructuring it,

Currently in the process of refactoring a NodeJS application to TypeScript. I have been consistently using object destructuring and have also been creating aliases while object destructuring, as shown in the code block below. My question is, how can I sp ...