What methods can be used to construct components using smaller foundational components as a base?

Is there a more elegant approach to constructing larger components from smaller base components that encompass common functionalities, akin to an interface in the OOP realm?

I'm experimenting with this concept, but it feels somewhat inelegant.

ReportItem.vue - The foundational component

<template>
  <div class="report-item">
    <div class="report-item__actions">
      <button @click="onEdit" type="button">Edit</button>
      <button @click="onDelete" type="button">Delete</button>
    </div>
    <div class="report-item__content">
      <slot></slot>
    </div>
  </div>
</template>
<script>
import '../styles/_report-item.css';
export default {
  name: 'report-item',
  props: {
    data: Object,
    type: String,
  },
  methods: {
    onEdit() {
      console.log("Editing...")
    },
    onDelete() {
      console.log("Deleted");
    }
  }
}
</script>

ReportItemText - the extended component that inherits the editing and deleting functionalities while adding additional content.

<template>
  <report-item class="report-item--title">
    <h4>{{title}}</h4>
  </report-item>
</template>
<script>
import ReportItem from './ReportItem';
export default {
  name: 'report-item-title',
  components: {ReportItem},
  data() {
    return {
      title: 'Report Title'
    }
  }
}
</script>

Could mixins or .extend offer a more robust solution while still allowing for template customization? Here is a link to a codesandbox illustrating the current implementation using this methodology - https://codesandbox.io/s/4jmw1l7xow

Answer №1

When it comes to creating a dynamic Vue.js component, utilizing mixins is key, but don't forget about incorporating slots - specifically named and scoped slots.

Scoped slots allow you to access and manipulate children's properties within a defined scope, enabling you to adjust rendering as needed. Meanwhile, named slots offer complete flexibility in determining what content to render. Here's a simple example:

// child-component
<div>
  <slot :childInternalProperty="objectInData">
    {{ childInternalProperty.name }}
  </slot>
</div>

// main
<child-component> <!-- will display the name -->
</child-component>

<child-component> <!-- will display "Hello!" -->
  Hello!
</child-component>

<child-component> <!-- will display "Hello {the name} !" -->
  <template slot-scope="slotProps"> <!-- template inserted into child-component's slot -->
    Hello {{ slotProps.childInternalProperty.name }}!
  </template>
</child-component>

In essence, this approach allows you to personalize the child component's template externally using its data.

I hope this explanation serves you well. Best of luck!

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

Vue: event triggers malfunctioning and components unresponsive

I am new to Vue.js and I'm attempting to trigger an event from my grand-child component (card) to the child component (hand) and then to the parent component (main): card (emit play event) => hand (listen for play event and emit card-play event) ...

What is the best way to add methods to underscore without making them available globally?

Have you added multiple methods to underscore within your package? _.mixin({ foo: function() {}, bar: function() {} //etc }); If you're concerned about potential conflicts with the main application or other packages, what's the best way ...

Experience the dynamic synergy of React and typescript combined, harnessing

I am currently utilizing ReactJS with TypeScript. I have been attempting to incorporate a CDN script inside one of my components. Both index.html and .tsx component // .tsx file const handleScript = () => { // There seems to be an issue as the pr ...

Jquery unresponsive in AJAX form output presentation

I recently delved into the world of jquery and AJAX, and while I grasp most concepts, I'm struggling with a small code snippet. On my webpage, there is a summary of articles. Clicking on an article name triggers a popup window with detailed informati ...

directive ng-click not responding

drawer-card.html (template) <div class="drawer-card-wrapper"> <div class="drawer-card-icon" ngClick="dcCtrl.toggle()"> <i class="icon--{{ icon }}"/> </div> <div class="{{'drawer-card ' + (classesToAdd || '&apo ...

Change the value of the material slide toggle according to the user's response to the JavaScript 'confirm' dialogue

I am currently working on implementing an Angular Material Slide Toggle feature. I want to display a confirmation message if the user tries to switch the toggle from true to false, ensuring they really intend to do this. If the user chooses to cancel, I&ap ...

Tips for integrating new channels and categories using a Discord bot

Hey there! I'm trying to add channels and categories, but I can't seem to get the function ".createChannel" working. The console keeps telling me that the function doesn't exist. I've been referencing the documentation at https://discor ...

Why does the entire page in Next.JS get updated whenever I switch pages?

Currently, I am utilizing Next.JS to create a single-page application website in React. I have successfully set up routing (https://nextjs.org/docs/routing/dynamic-routes) In addition, I have also configured Layouts (https://nextjs.org/docs/basic-features ...

Issues arise when using PHP4 in conjunction with Ajax, the json_encode function, and

I have been tasked with a project for my company that requires PHP4 development. The goal is to display a list of mobile phone brands and their prices, as well as the ability to filter them using multiple checkboxes. However, I am facing an issue where the ...

Struggles with handling asynchronous events in Angular

I'm currently working on a piece of code that iterates through an array containing 10 items. For each item, a request is made and the returned data is stored in another array. The entire process goes smoothly until reaching the line that contains $q.a ...

Encountering a typescript error while configuring options in an Angular 8 application

When attempting to call a service using REST API with a GET request, I encountered the following error: Argument of type '{ headers: HttpHeaders; responseType: string; }' is not assignable to parameter of type '{ headers?: HttpHeaders | ...

The issue arises when nuxt.js is set to spa mode and the root path is not correctly configured on a

English is not my strong suit, apologies in advance. I have a Nuxt project set up like this. Operating in spa mode. Folder Structure pages - index.vue index |_ child.vue |_ index.vue pages/index.vue <template> < ...

unable to fix slideshow glitch after multiple cycles

I've encountered an issue with my custom JavaScript picture scroll. After 3-4 photo changes, the script crashes the page unexpectedly. I'm not sure what is causing this problem! Can someone provide assistance? Below is the code snippet: <di ...

Is there a way to dynamically alter a Vue component based on time? When I say alter, I am referring to one component replacing another, similar to how a carousel functions

Is there a way to make the widgets on my Vue website cycle every few seconds, like in a carousel? I want them to replace each other periodically. What is the most effective method for accomplishing this? ...

Connecting a JavaScript script from my HTML file to Django's static files - here's how

I recently started a Django project with frontend code that wasn't initially written for Django. I am having trouble connecting this script: <script> document.body.appendChild(document.createElement('script')). src='js/ma ...

Steps to integrate the Save as PNG functionality in Vega using a customized menu

As I develop a data dashboard with Vega for visualizing outputs, I decided to customize the menu system by removing the actions dropdown. However, I still want to incorporate the "Save as PNG" option from the original dropdown (as shown in the image below) ...

Application experiencing server error when updating MongoDB data

I have encountered an issue while trying to update/modify data that has already been uploaded in a reactjs project using mongoDB as the database. Whenever I attempt to update the data, an error is displayed. How can this problem be resolved? https://i.sta ...

Using Vue.js to alter the CSS class property

I am exploring Vue.js and looking to modify a CSS class property. Here is the HTML code utilizing the specified class: <div class="customTimer"></div> Here is the corresponding CSS code: .customTimer { width: 100%; height: 1 ...

Tips for ensuring text remains within a div container and wraps to the next line when reaching the edge

Currently, I am working on a flash card application using Angular. Users can input text in a text box, and the text will be displayed on a flash card below it. However, I have encountered an issue where if the user types a lot of text, it overflows and mov ...

Is it advisable to modify the value of props by using toRef in the Composition API?

I've noticed a common practice in the CompositionAPI where props are converted to refs using `toRefs` function. This has left me feeling a bit confused. For instance, citing the Vue 3 official guide: export default { props: { user: { type ...