Component properties for the Vuetify 3 wrapper

Currently, I am in the process of wrapping various Vuetify components into a custom component to gain better control over the application's appearance and behavior. However, I have encountered an issue where default props for the Vuetify component work well, but when additional props are added during consumption of the component, these override props are not being utilized.

Using Vue 3.2.38 and Vuetify 3.1.10.

Custom Component:

<template>
  <label v-if="name">{{ name }}</label>
  <v-text-field v-bind="{ ...$attrs, ...$props, ...defaultProps }">
    <template v-for="(_, scopedSlotName) in $slots" #[scopedSlotName]="slotData">
      <slot :name="scopedSlotName" v-bind="slotData" />
    </template>
    <template v-for="(_, slotName) in $slots" #[slotName]>
      <slot :name="slotName" />
    </template>
  </v-text-field>
</template>

<script lang="ts">
import { defineComponent } from 'vue';
import { VTextField } from 'vuetify/components/VTextField';

export default defineComponent({
  name: 'EmailField',
  extends: VTextField,
  props: {
    name: {
      type: String,
      default: ''
    }
  },
  computed: {
    defaultProps() {
      return {
        color: 'yellow',
        bgColor: '#252836',
        variant: 'outlined',
        density: 'compact'
      };
    }
  }
});
</script>

Consuming the component:

<template>
  .......other template items

  <EQEmailField v-model="email" name="Email Address" counter :persistentCounter="true"  color="blue" density="comfortable" />
  
</template>

<script lang="ts">
import { defineComponent, defineAsyncComponent } from 'vue';

export default defineComponent({
  components: {
    EmailField: defineAsyncComponent(() => import('@/components/custom/email-text-field.vue'))
  }
});
</script>

The default props (defaultProps) set within the component function correctly and apply to Vuetify as expected. Challenges arise when consuming the component and attempting to use passed props to override default ones. In this scenario, the default props always take precedence, and the consumer-side props are neglected. Attempts to override a value already defined in defaultProps prove unsuccessful, while adding new props works without issues. It seems like there is a need to navigate through the props and determine which should be applied. While this may pose a challenge, it appears to be a common occurrence that needs to be addressed.

Answer №1

To set default values for props, list them in a computed property like this:

export default defineComponent({
  name: 'EmailField',
  extends: VTextField,
  props: {
    name: {
      type: String,
      default: ''
    },
    color:{
      type:String,
      default:'yellow'
    },
   //repeat the same process for other props
  },
    
});

Then in your template, bind the props using the spread operator:

<v-text-field v-bind="{ ...$attrs, ...$props}">

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

Retrieving data simultaneously from two MongoDB collections

I want to fetch data from 2 collections and combine them into a single array with merged data. The solution that worked for me was: const bothValues = await ValueA.aggregate([ { $unionWith: { coll: 'valueB' } }, { $sort: { rank: -1, ...

jQuery fails to make a POST request when the content type is set to application/json

I am utilizing jQuery version 1.10.1. My goal is to execute a POST request with the content type set to application/json. The code I have implemented is as follows: $.ajax({ type: "post", url: urlBase + "user/search", contentTy ...

Encountering a npm failure during the installation process of polymer

I'm currently attempting to test sensors using HTML and JavaScript, following the example provided here. However, I encountered an issue when trying to install polymer as instructed in the readme file. The error I received is as follows: kupu@kupu:~/ ...

The utilization of Node.js promises combined with a for loop

I have managed to make progress, but I seem to be stuck once again. The issue lies with my for loops not functioning as expected. When there are three roles, only the last one is being added (three times) to my pivot MySQL table due to its asynchronous na ...

Stack overflow error caused by computed property setter exceeding the maximum limit of the stack

The following code snippet is giving me trouble: <div id="app"> <b-form-group label="Sorting"> <b-form-checkbox-group v-model="sorting" :options="filterData.sorting" /> </b-form-group> </div> ...

Unresolved issue with RxJS - Finalize not triggering

When attempting a logout request, I have encountered an issue where the same actions need to be dispatched regardless of whether the request is successful or fails. My initial plan was to utilize the finalize() operator for this purpose. Unfortunately, I ...

Is it possible to retrieve the user's input value within a custom filter? I am attempting to access the user's input number either from the controller or

I am a beginner in AngularJS and I am attempting to filter data based on temperature by subtracting the user input (x) from the currentTemp variable. However, I am unsure how to access the user input value in a custom filter. This approach may work for now ...

When using JavaScript, links within the window.location are automatically altered

When using window.location (.assign, .replace, .href) to redirect to a product page on click, I encountered an issue where it automatically changes some of the href links. For example: instead of "previous href= 'commercial/fonts/fonts.min.css' ...

Unable to retrieve fileReader result value within AngularJS service

I am currently in the process of developing a service that reads image files from an HTML input element. The goal of this service is to return the HTML img object with the updated attribute containing the base64 string of the read image file. Below is the ...

Error encountered during conversion from JavaScript to TypeScript

I am currently in the process of converting JavaScript to TypeScript and I've encountered the following error: Type '(props: PropsWithChildren) => (any[] | ((e: any) => void))[]' is not assignable to type 'FC'. Type '(a ...

Using JavaScript to obtain the coordinates of a click event from a programmatically triggered click on an HTML element

Is there a way to programmatically simulate a click event on an HTML DOM element and still retrieve the screenX/screenY and clientX/clientY coordinates successfully? When manually clicking the element, the coordinates are visible in the console, but when t ...

"Exploring the possibilities of integrating the Twitter API with

Currently, I am attempting to access my most recent tweet from Twitter using https://github.com/jdub/node-twitter I am interested in setting a variable, modifying that variable within a function, and then utilizing it again outside of said function. Is th ...

What is the process for duplicating a div container when a button is clicked?

http://jsfiddle.net/TDmRv/1/ My Goal: I aim to have the input text wrapped in a div with the id "theDiv" every time it is added to the page. This way, the text will be displayed within multiple dynamically created divs. Further Explanation: Essentially, ...

The issue arises when using NestJs with Fastify, as the code does not continue executing after the app.listen()

Greetings everyone, this is my inaugural question on this platform, so please forgive any oversights on my part. I have a query regarding my NestJs application configured to run with Fastify. Unlike Express, the code after the app.listen('port') ...

What is causing the CSS transition to fail in the updated DOM?

When attempting to apply a CSS transition as shown in the following code snippet: https://jsfiddle.net/sunyuu/e58sfeva/17/ var Main = { data () { return { isActive: false, childStyle: {} }; }, methods: { sho ...

Discovering the identical element within the ajax response

The following section is being targeted: var obj = $(this).parent().find('a'); // $(this) is a <UL> inside a <DIV>, but there can be multiple DIV>ULs on the page After that, I retrieve some HTML using $.ajax(). This HTML corres ...

What should be the proper service parameter type in the constructor and where should it be sourced from?

Currently, I am faced with a situation where I have two Angular 1 services in separate files and need to use the first service within the second one. How can I properly type the first service in the constructor to satisfy TypeScript requirements and ensure ...

Convert JavaScript object into distinct identifier

I have a data object where I'm storing various page settings, structured like this: var filters={ "brands":["brand1","brand2","brand3"], "family":"reds", "palettes":["palette1","palette2","palette3"], "color":"a1b2" }; This object is ...

Tips for creating a script that is compatible with both Java and C++

We currently offer both Java and C++ versions of our distributed messaging system product. I am in the process of developing a framework to conduct system testing across multiple servers. In order to accomplish this, I need a "test coordinator" process th ...

issues with responsive mobile navigation

Greetings! I've been diligently working on a website project for a client, but I have a nagging feeling that I may have overlooked something important. If you'd like to take a look at the small design mockup preview I'm providing for the cl ...