What is the best method for sharing templates and logic in VUE?

Two separate components with shared logic and template, making it appear as though one is extending the other.

Think of Drop and Pick components in this manner:

// pick.js
import Vue from 'vue'
import Component from 'vue-class-component'

@Component
export default class Pick extends Vue {
  template: '<p>{{name}}</p>',
  created() {
    console.log('Hello Pick');
  }
  data: { 
    name: 'pick',
    count: 0
  },
  methods: {
    add: function () {
      this.count++;
    }
  }
}

// drop.js
import Vue from 'vue'
import Component from 'vue-class-component'

@Component
export default class Drop extends Vue {
  template: '<p>{{name}}</p> <span v-if="isUserFriendly">Greetings!!!</span>',
  created() {
    console.log('Hello Drop');
  }
  data: { 
    name: 'drop',
    isUserFriendly: false,
    count: 0,
    drops: 0
  },
  methods: {
    add: function () {
      this.count++;
      this.drops++;
    },
    remove: function () {
      this.count--;
    },
  }
}

Initially, it may seem like Drop is extending Pick while adding extra functionality and modifying the template. However, forcing Pick to include information about isUserFriendly goes against the concept of unrelated context components.

This approach could lead to maintenance challenges down the line if more components are extended and shared logic increases.

Do you have any suggestions for a better solution? Is there another method that I am not familiar with?

Thank you for your input!

Answer №1

Utilizing component composition is a widely used method for achieving this goal. The Drop component consists of a comprehensive set of functionalities, whereas the Pick component can be wrapped in a manner that enables the desired output and behavior.

When establishing a parent-child relationship, data components are transmitted through props and events, while view components are transmitted through slots.

The parent component retains any additional logic.

Within the child component (Pick):

<div>
  <p>{{name}}</p>
  <slot name="extraText"/>
</div>

Additionally,

add: function () {
  this.count++;
  this.$emit('add');
}

In the parent component (Drop):

<Pick @add="drops++">
  <template v-slot:extraText>
    <span>Greetings!!!</span>
  </template>
</Pick>

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

What is the best way to create a sortable column that is based on a nested object within data.record?

I am utilizing jquery jtable to showcase some data in a table. I have been using the following code snippet for each field in the table to display the data and enable sorting: sorting: true, display: (data) => { return data.record.<whatever_value ...

I require the ability to access a reference parameter with a dynamically changing name within a Vue template

<div v-for="x in 4" :class="(images[x] === null) ? 'not-removable' : 'removable'" class="img-container"> <input style="display: none" type="file" ...

How can I extract a standalone CSS file from a single SCSS file using VueCLI and Webpack?

Currently, I am working on an app using VueCLI and webpack. The main.js file contains all the vue components and scss assets which compile into global .js and .css files as expected. In addition to this setup, there is a requirement for a single example.s ...

Adding a character at the beginning of each loop iteration in a nested array with Vue.js

When working inside a v-for loop, I am attempting to add a character at the beginning of each item in a nested array that may contain multiple items. I have explored various options but have not been successful: :data-filter="addDot(item.buttonFilter ...

Utilizing Regular Expressions as a Key for Object Mapping

Currently, I am facing a challenge in mapping objects with keys for easy retrieval. The issue arises when the key can either be a string or a RegExp. Assigning a string as a key is simple, but setting a regex as a key poses a problem. This is how I typica ...

using outlines for FontAwesome icons in React Native

I am struggling to use the fontAwesome + icon in the middle of a circle as one item. I have tried placing it inside a circle icon, but it doesn't seem to work properly. import IconFA from 'react-native-vector-icons/FontAwesome'; < ...

Compose an email in Vue.js without relying on any third-party API integration

Looking to send emails via SMTP Protocol without relying on any third-party integrations or APIs. Please provide a detailed, step-by-step solution. No need for existing code reflection, just ensuring error-free execution. ...

Receiving Server Emissions in Vue/Vuex with Websockets

In my Vue component, I was using socket.io-client for WebSocket communication. Now that I've added Vuex to the project, I declared a Websocket like this: Vue.use(new VueSocketIO({ debug: true, connection: 'http://192.168.0.38:5000', })) ...

Dealing with yarn warnings effectivelyIf you want to resolve

I recently set up a new Vue project using the vue cli, incorporating Vue3 with Ant Design, Vue Router, and Eslint. However, upon running the yarn command, I encountered some warnings: yarn install v1.22.10 [1/4] Resolving packages... [2/4] Fetching package ...

How can a TypeScript Angular directive utilize a function?

Recently, I have been following a unique Angular directive TypeScript pattern that I find really effective. The approach involves giving the directive its own isolated scope by creating a new controller. I encountered a scenario where I needed to invoke a ...

What are the reasons for the inability to send form-data in Postman?

Encountering an issue when trying to send form-data in postman as Sequelize returns an error: value cannot be null However, everything works fine when sending a raw request with JSON. Have tried using body-parser and multer, but no luck. This is my inde ...

Are auto-properties supported in TypeScript yet?

I've heard that properties in Typescript can be defined like they are in C# with automatic setters and getters. However, I have found it difficult to implement properties this way as the intellisense does not support such syntax in Typescript. I tried ...

Transitioning React components organized in groups to TypeScript

As I transition my react project to incorporate typescript, one challenge I encountered was adjusting the file structure. In its simplified form, here is how the original js project's file structure looked like: src components index.js inputs butt ...

What methods can I use to ensure that both variables are true and maintain their relationship in a logical 'and' statement?

The code snippet provided raises a question about the logic behind the declaration of variable x as a string: function sample(one: boolean, two?: string) { if (one || two) { const x: string = one ? 'hello' : two; // Type 'string | ...

Troubleshooting image loading issues when updating the base URL in an Angular JS project

I am trying to update the base URL for my application. Currently, when I load the application, the URL shows up as http://localhost:4200/#/, but I want it to be http://localhost:4200/carrom/ instead. To accomplish this, I modified the base URL and now th ...

[Vuetify alert]: The server-side rendered virtual DOM structure does not align with the client-side content (Nuxt, Vue, and lerna monorepo)

I am currently facing an issue while attempting to run a basic Nuxt application within a lerna monorepo, which includes an external Vue component constructed using vue-cli. Initially, the page displays the content of the component (rendered by the server) ...

Loop through a series of objects using a for loop

I need help with looping through a set of objects using a for loop, but I'm encountering an issue because they do not have the same name. <div id="components-demo"> <div>Travel Information</div> <ul> <li ...

Angular2 ngIf directive issue after initial button click

I have recently started using the Angular2 Framework, so please bear with me if I make any common mistakes. I have set up two forms in separate div tags: one for logging in and another for password reset. Below the login form, there is a link that, when cl ...

Designing a node module that allows access to various extended classes written in separate CoffeeScript files

I am interested in creating a single-node library that consists of multiple classes, each written in coffee-script and stored in separate files within node_modules/mymodule/src directory. To illustrate, consider the following file structure: File 1: clas ...

Incorporating a skeletal design effect into a table featuring sorting and pagination options

Is there a way to implement the Skeleton effect in a MUI table that only requires sorting and pagination functionalities? I tried using the 'loading' hook with fake data fetching and a 3-second delay, but it doesn't seem to work with DataGri ...