Tips for efficiently utilizing a Vue.js component with numerous props and slots

Within a vuejs application, there exist three components - TopClicks.vue, TopImpressions.vue, TopCtr.vue. Each of these components utilizes vue-good-table for rendering a similar table with varying sorting techniques:

../components/TopClicked.vue (around 200 lines)

<template>
  <div class="top-clicked">
    <vue-good-table
      mode="remote"
      @on-page-change="onPageChange"
      @on-sort-change="onSortChange"
      :sort-options="{
        enabled: true,
        initialSortBy: {field: 'clicks', type: 'desc'}
      }"
      ... 
    >
      <template slot="table-row" slot-scope="props">
        <template v-if="props.column.field === 'keyword'">
          ...
        </template>
        <template v-else-if="props.column.field === 'clicks'">
          ...
        </template>
        <template v-else-if="props.column.field === 'impressions'">
          ...
        </template>
         ...
      </template>
      <template slot="loadingContent">
        <span class="vgt-loading__content">
          ...
        </span>
      </template>
      <template slot="emptystate">
          ...
      </template>
    </vue-good-table>
  </div>
</template>

<script>

import { VueGoodTable } from 'vue-good-table';

export default {
  name: 'TopClicked',
  components: { VueGoodTable},
  data() {
    return {
      columns: [
        {
          label: this.$t('keyword'),
          field: 'keyword',
        },
        {
          label: this.$t('clicks'),
          field: 'clicks',
        },
        ... more columns
      ],
    };
  },
};
</script>

The other two components - TopImpressions.vue and TopCtr.vue are nearly identical, except for the different values passed to the :sort-options parameter.

The main query at hand is: How can the code be structured to avoid redundant changes in the props or slot templates of the vue-good-table component? What should a component look like that passes default props and slots to another component, while allowing for override when necessary?

It would be beneficial if instead of duplicating the aforementioned 200 lines of code, a child component (with base properties and slot templates) could be created and utilized as shown below

<vue-good-table-child
  // intended to override the default :sort-options in vue-good-table-child
  :sort-options="{
    enabled: true,
    initialSortBy: {field: 'impressions', type: 'desc'}
  }"
>
  // meant to override the default named slot "loadingContent" in vue-good-table-child
  <template slot="loadingContent">
    ...
  </template>
</vue-good-table-child>

This approach ensures that common code remains in a base component, with only distinct props (or slot templates) being passed to the child component.

Answer №1

To improve efficiency, consider consolidating the 3 similar components into a single component that can receive customized sortOptions as a prop:

// Consolidated component - TopThings.vue replaces TopClicks.vue, TopImpressions.vue, and TopCtr.vue in the parent component

<template>
<div class="top-clicked">
    <vue-good-table
        ...
        :sort-options="sortOptions"
        ...
    />
    ...
</template>

<script>
    ...
    props: {
        sortOptions: {
            type: Object,
            required: true,
        },
    },
    ...
</script>

In the parent component, import the TopThings component and use it instead of the previous 3 components, passing specific sortOptions to each one:

// Parent component implementing the 3 tables with instances of <TopThings />

<template>
    ...
    <TopThings // TopClicks implementation
        :sort-options="sortOptions.topClicks"
    />
    ...
    <TopThings // TopImpressions implementation
        :sort-options="sortOptions.topImpressions"
    />
    ...
    <TopThings // TopCTR implementation
        :sort-options="sortOptions.topCTR"
    />
    ...
</template>

<script>

components: {
    TopThings.vue,
},
data() {
    return {
        sortOptions: {
            topClicks: {
                enabled: true,
                initialSortBy: {field: 'clicks', type: 'desc'}
            },
            topImpressions: {
                ...
            },
            topCTR: {
                ...
            },
        },
    };
},

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

Error message: "Window is not defined in Next.js"

Can anyone help me with this issue I'm experiencing: 'window is not defined' error? useEffect(() => { const handleScroll = () => { if(typeof window !== 'undefined') { // scrolling dete ...

Is there a way for me to retrieve a variable from within a .then function nested within another .then function?

Here is an example of code where I am attempting to log the value of 'a' to the console. driver.sleep(2000).then(function logAInConsole() { var a = ["Quas","Wex","Exort","Invoke"]; for(var i = 0; i < a.length; i++) { driver.sleep( ...

Concealing the label for a specific component in Vue/Nuxt JS

I have developed a reusable input component that includes a label. However, I need the label to be hidden in certain instances (without taking up space, similar to using display:none in CSS), while remaining visible in others. Below is the code for my inp ...

Is there a way to alter the CSS padding class for collapsed elements?

I've created a navbar by following Bootstrap's tutorial, but I'm facing an issue with the padding. I used the Bootstrap class "pe-5" to add padding to a form within the navbar so that it aligns to the right with some space from the screen ed ...

Issue with the height of sections in the active menu

While the set-up below is functional for content within section height limits, it fails when exceeding the limit causing overflow. Adding "display: table" or "overflow: hidden" to fix the overflow issue affects the menu's active state behavior. Sett ...

I often struggle with creating social media buttons using Material UI

https://i.sstatic.net/jmZKS.jpg https://i.sstatic.net/4RQwe.jpg Unfortunately, the code provided is not rendering social media icons or buttons as expected. In the initial lines, material UI icons/buttons were imported from the React Material UI library ...

Using jQuery AJAX to send data containing symbols

When making an AJAX call, I am including multiple values in the data like this: var postData = "aid="+aid+"&lid="+lid+"&token="+token+"&count="+count+"&license="+license; postData = postData + "&category="+category+"&event_name="+e ...

Creating code to ensure a div element is displayed only after a specific duration has elapsed

Can anyone help me with coding to make a div appear on a website after a specific amount of time? Here's an example of what I'm trying to achieve: <div class="container"> <div class="secretpopout"> This is the hidden div that should ...

Issues arising from using async/await in conjunction with .then() in vue.js login function, causing fetch process not to wait for completion

I implemented a login function to verify credentials on my backend server, but I am facing an issue with waiting for the server response. Despite following the es7-async-await.js guide and trying various async/await and promise techniques, the function sti ...

Combining Bootstrap Vue: utilizing class names alongside HTML tags

(Bootstrap-Vue 2.0, Vue.js 2.5) Is it possible to combine traditional CSS Bootstrap 4 classes with Bootstrap-Vue? For example, can I use the following code snippet: <section id="introduction"> <b-container class="h-100"> & ...

Error: Cannot locate module: Vue not found, incorrect path specified

I am facing an issue with my webpack configuration. I have placed my webpack.config.js and node_modules in a subfolder. When attempting to run the command npm run build, I encounter the following error: ERROR in ../public/Vue/Components/Rating.vue Module n ...

How can you transform this jQuery snippet into a unique Javascript function?

I've managed to get this code to work, but I'm looking for a way to streamline it using a JavaScript function. This would save me the hassle of writing it out repeatedly. $("#portfolio").waypoint(function() { for (var i = 0; i <= 8; i++) ...

Node.js allows for the halting of statement execution if it exceeds a predetermined time limit

Is there a way to pause the execution of a statement if it exceeds a certain time limit? I need help with this problem. In the code snippet below, if the statement const result = await curly.get('www.google.com'); takes longer than 2 seconds to ...

Having difficulty utilizing the express.session module in conjunction with HTTPS

I need to implement authentication and session creation on a HTTPS static website using expressjs. Here is the code snippet: app.js: // Set up the https server var express = require('express'); var https = require('https'); var http ...

Encountering a hindrance with NPM proxy while attempting to globally install Vue CLI

I have encountered an issue while trying to install Vue Cli globally. The installation process is not completing and I am receiving errors related to proxy settings. I tried to manually add values to the .npmrc file as shown below, but it did not resolve t ...

Trouble with locating newly created folder in package.json script on Windows 10

I am facing an issue in my Angular application where I am trying to generate a dist folder with scripts inside it, while keeping index.html in the root folder. I have tried using some flag options to achieve this but seem to be stuck. I attempted to automa ...

How can I turn off popover when I am moving an event?

Is there a way to hide the popover element when dragging an event in fullcalendar, and then show the popover again after the dragging is stopped? Here is the code I am currently using: eventRender: function(event, elementos, resource, view) { var ...

Testing a close function in a modal using Karma-jasmine

Testing is new to me and I'm looking to test the close function and see if it renders properly in Angular. Here's the HTML structure: <div class="modal active" *ngIf="active" id="modal"> <div class=" ...

The nonce parameter is not permissible for this specific message type

I am currently implementing nuxt-auth in my Nuxt.js project. check out the image description here ...

generate new content for a webpage by clicking on a product

Hello everyone, I am currently in the process of creating a website dedicated to t-shirts. Utilizing a JSON file, I have successfully set up dynamically generating preview cards for each product. However, I now face the challenge of needing to generate c ...