Extending the rules and requirements of VInput

Currently, I am utilizing Vue+Vuetify and facing the task of revamping a custom selector component.

The existing code structure is as follows:

<template>
  <v-autocomplete
    :id="id"
    v-model="internalValue"
    :clearable="clearable"
    :disabled="disabled"
    :hide-details="hideDetails"
    :label="label"
    :readonly="readonly"
    :required="required"
    :rules="rules"
    :items="items"
    item-value="id"
    item-text="name"
    no-data-text="No data"
  />
</template>

<script>
export default {
  name: 'MyCustomSelector',
  props: {
    value: {
      type: String,
      default: null,
    },
    label: {
      type: String,
      default: '',
    },
    id: {
      type: String,
      default: null,
    },
    required: Boolean,
    clearable: Boolean,
    hideDetails: Boolean,
    disabled: Boolean,
    readonly: Boolean,
  },
  data() {
    return {
      items: [],
      rules: [
        (value) => {
          if (this.required) {
            return !!value || 'This field is empty'
          } else {
            return true
          }
        },
      ],
    }
  },
  apollo: {
    // apollo logic
      ...
      this.items = loadedItems
      ...
  },
  computed: {
    internalValue: {
      get() {
        return this.value
      },
      set(newVal) {
        this.$emit('input', newVal)
      },
    },
  },
}
</script>

The majority of the code involves passing props, so I made the decision to transform it into:

<script>
import VAutocomplete from 'vuetify/lib/components/VAutocomplete'

export default VAutocomplete.extend({
  name: 'MyCustomSelector',
  props: {
    itemText: {
      type: String,
      default: 'name',
    },
    itemValue: {
      type: String,
      default: 'id',
    },
    rules: {
      type: Array,
      default: () => [
        (value) => {
          if (this.required) {
            return !!value || 'This field is empty'
          } else {
            return true
          }
        },
      ],
    },
    noDataText: {
      type: String,
      default: 'No data',
    },
  },
  apollo: {
    // apollo logic
      ...
      this.cachedItems = loadedItems
      ...
  },
})
</script>

Although everything seems to be in order, there exists a small issue - the prop rules does not function as intended since this.required is unrecognized.

This prop is derived from the Validatable mixin, where the value from the field is simply substituted sequentially to each of the rules.

Hence, my query pertains to crafting code wherein the behavior of the rule hinges on the state of the required field?

Answer №1

To retrieve the prop's data, opt for a conventional function over an arrow function

 rules: {
  type: Array,
  // replace with a traditional function
  default: function () {
    return [
      (value) => {
        if (this.required) {
          return !!value || "This field is empty";
        } else {
          return true;
        }
      },
    ];
  },
},

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

Button inside a React JS Material UI autocomplete chips component

https://i.sstatic.net/BS4yB.png The image above showcases two input fields with autocomplete functionality. The first field effectively uses chips for autocomplete suggestions. However, the second field features an autocomplete but is non-functional, with ...

Utilizing HTML5 to Access and Update custom data attributes

I have implemented the following code: var activeFilter = $('<li></li>').data('input-id', 'mycustomId'); $('#container').append(activeFilter); Now, I am faced with the challenge of retrieving a specific ...

`Downloading npm package while on vpn is proving difficult`

Whenever I attempt to download a package from npm (or yarn) while connected to a VPN (I use Psiphon) in either VScode or my Command Prompt (I'm on Windows 10), it never seems to work. Instead, after some time, I receive an error message like the follo ...

The Prototype of a Variable: Its Intrinsic Value

I have a basic prototype and I am looking to continuously update the 'Balance' value as payments are made. Can anyone advise me on how to maintain the 'Balance' variable using HTML, CSS, Javascript, and Bootstrap? After clicking Submit, ...

Form that adjusts input fields according to the selected input value

I am in need of creating a dynamic web form where users can select a category and based on their selection, new input fields will appear. I believe this involves using JavaScript, but my searches on GitHub and Stack Overflow have not yielded a suitable sol ...

Delightful Popup for Successful Woocommerce Additions

I have created a plugin that transforms Wordpress Woocommerce variations into a table layout. I made significant changes to the code and now I'm attempting to integrate Sweet Alerts 2 in place of the current alerts displayed when a user adds a product ...

What is the best way to access a ViewChild element in the parent component without rendering it?

I am currently utilizing a component within another component in the following manner: <inline-help> <help-title>{{::'lang.whatIsThis'|i18n}}</help-title> <help-body i18n="lang.helpBody">& ...

Sending user input data from a React text field to a function as arguments

Below are input fields, from which I need to retrieve the entered values and pass them to the onClick event of the button displayed below. <input type="text" style={textFieldStyle} name="topicBox" placeholder="Enter topic here..."/> <input type=" ...

How to send arrays through JSON?

I have some PHP code: $ids = array(1,2,3); $names = array("cat","elephant","cow"); $originalSettings = array ('ids'=>$ids,'names'=>$names); $jsonSettings = json_encode($originalSettings); echo $jsonSettings; Here ...

Determining element visibility in React

Please refrain from flagging this as a duplicate. While it may be similar to other questions, I am specifically inquiring about the location to place the code, not how to write it. Here is the code I have and my goal is to determine which section is curre ...

Unable to use the .focus() method on a Link component by utilizing references in React Router 4

I am currently working with the Link component in react-router (v4). I have successfully attached a ref to this component and can log the reference. However, when I try to use linkRef.current.focus(), I encounter the following error: linkRef.current.focu ...

The console logs indicate true, yet contradicts with a false assertion in the if statement

I am facing an issue with this code router.get("/timecard", ensureAuthenticated, async(req, res)=>{ users = await User.find(); console.log(req.user.cwlEmployee); if(req.user.cwlEmployee !== true){ req.flash('error_msg', &a ...

Tips on utilizing the ternary operator when binding in Vue

<label class="switch"> <input type="checkbox" v-on:change="updateRequiredData(list.input_permission_id,selected, selected == 'Applicant' ? list.status : selected =='Guaranter' ? list.guaranter_required : selected ='Refer ...

Obtain non-numeric parameters from the URL in Angular 2 by subscribing to

How do I handle subscribing to a non-numeric parameter from a URL? Can the local variable inside my lambda function params => {} only be a number? Here's my code: getRecordDetail() { this.sub = this.activatedRoute.params.subscribe( ...

Why isn't the color of the circle changing in the console when I type this.fill = "black"?

I am creating circles as a hobby, using a function to generate them. However, I am facing an issue with changing their parameters in the console after creation. Specifically, I am unable to change them in this manner and I'm wondering why not. a.fill ...

Guide to showcase Material UI drawer with a margin at the top

I'm having trouble implementing a Material UI drawer with some top margin instead of starting from the very top of the page. I've tried applying the marginTop property, but it's not working. You can view my code on CodeSandbox here: Drawer. ...

Retrieving all users in Sqlite database with a specific value

I am looking to identify and access each user who has a specific value in their row. Here is an example code snippet of what I want: sql.prepare("SELECT * FROM raid WHERE raid1 > 0 AND NOT id='685337576810610734'").get().forEach(async (user) ...

What is the reason why setting 'onClick' as an event handler is not flagged as a syntax error?

I am currently working on a JavaScript code snippet where I am trying to change the headline text when it is clicked. The code I have written is: var headline = document.getElementById("mainHeading"); headline.onClick = function() { headline.innerHTML ...

How can we display data from the database in a table if the data is stored as a string separated by commas using Ajax?

I am having trouble displaying 33 and 123 of heading 1 and heading 2 in a new row. Can someone please help me with this issue? Even though I updated the code, the for loop is only showing the last value. $.ajax({ type:"POST", url:"{{route(&ap ...

Calculating distinct values within a single key in an object

My goal is to track the occurrences of four specific string values within the same key. The issue lies in my struggle with adding multiple counters. While the first counter successfully tracks the initial condition, subsequent conditions within the if/els ...