The functionality of the <select-vue> component in Vue.js does not support null values

custom-select.vue

<template>
  <div class="relative">
    <label
      :for="$attrs.name"
      class="block text-sm font-medium leading-6 text-gray-900"
      >{{ $t($attrs.label) }} {{ required ? '*' : '' }}</label
    >
    <i
      v-if="!disabled"
      class="fa-light absolute right-3 top-11 fa-chevron-down"
    ></i>
    <select
      @input="changed"
      :value="value"
      :disabled="disabled"
      :class="errorInputStyle"
      v-bind="$attrs"
      class="mt-2 appearance-none disabled:cursor-not-allowed disabled:bg-gray-100 outline-none disabled:text-gray-600 disabled:ring-gray-200 bg-white block shadow w-full rounded-md border-0 py-2 pl-3 pr-10 ring-1 ring-inset focus:ring-2 sm:text-sm sm:leading-6"
    >
      <option :selected="value === defaultValue" :value="defaultValue" disabled>
        {{ $t($attrs.placeholder) || 'please select' }}
      </option>
      <option
        :selected="option.value === value"
        :value="option.value"
        v-for="option in options"
      >
        {{ $t(option.text) }}
      </option>
    </select>

    <p :class="errorDescriptionStyle" class="mt-2 text-sm">
      {{ $t($attrs.description) }}
    </p>
  </div>
</template>

<script lang="ts">
import { computed, onMounted, ref } from 'vue'
import { BaseOptionT } from '~/types'

export default {
  props: {
    value: {
      default: '',
    },
    options: {
      default: () => [] as BaseOptionT[],
    },
    required: {
      default: false,
    },

    disabled: {
      default: false,
    },
    isError: {
      default: false,
    },
  },

  setup(props, { emit }) {
    let selectValue = ref('')
    let defaultValue = ref()
    function changed(e: any) {
      let target = e.target as HTMLSelectElement

      try {
        return emit('input', JSON.parse(target.value))
      } catch (err) {
        return emit('input', target.value)
      }
    }
    let errorDescriptionStyle = computed(() => [
      props.isError ? 'text-red-500' : 'text-gray-500',
    ])
    onMounted(() => {
      if (!props.options.some((o) => o.value === props.value)) {
        defaultValue.value = props.value
      }
    })
    let errorInputStyle = computed(() => [
      props.isError
        ? 'text-red-900 ring-red-300 placeholder:text-red-300  focus:ring-red-600'
        : 'text-gray-900 ring-gray-300 placeholder:text-gray-300  focus:ring-green-600',
    ])
    return {
      changed,
      defaultValue,
      selectValue,
      errorDescriptionStyle,
      errorInputStyle,
    }
  },
}
</script>

Here is the situation:

<custom-select v-model="group.billing_waiting_period" :options="billWaitingPeriods" />

Whenever I use my component like this, and in this specific case billing_waiting_period Exists but contains a value of null, Vue fails to update the user interface when I choose something different from the dropdown. The group object is a prop

Here is additional context:

    let billWaitingPeriods = computed(() =>
      Object.values(BillWaitingPeriod).map((interval) => {
        switch (interval) {
          case BillWaitingPeriod.ONE_MONTH:
            return { value: interval, text: '1 Month' }
          case BillWaitingPeriod.TWO_MONTH:
            return { value: interval, text: '2 Months' }
          case BillWaitingPeriod.THREE_MONTH:
            return { value: interval, text: '3 Months' }
          default:
            return { value: interval, text: '1 Month' }
        }
      })
    )

export enum BillWaitingPeriod {
  ONE_MONTH = "ONE_MONTH",
  TWO_MONTH = "TWO_MONTH",
  THREE_MONTH = "THREE_MONTH"
}

Answer №1

It's a big no-no to modify the prop in Vue! It seems like you're attempting to change one property of a prop, but that is not allowed and will not be effective. Instead, consider emitting an event.

const waiting_period = computed({
  get: () => group.waiting_period,
  set: val => emit("update:group.waiting_period", val)
})

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

Transferring an array from a server to a client using socket.io

I'm working on a small chat application and I want to show a list of users who are currently connected. On the server side, I have the following code snippet: var users = {}; io.on('connection', function(socket){ socket.on(&apo ...

What is the most stylish method for merging a removeCartItem function with an addCartItem function?

Is there a way to combine these functions into a more concise and elegant piece of code? While the current setup works fine, it feels redundant to have two large functions that essentially do the same thing. const modifyCartItem = (cartItems, productToMo ...

Retrieve the event object from the VueJS global event bus

I am facing a situation where I have multiple pages in Laravel, each containing a form with different action URI's: <form method="post" action="/route1"> ... <button @click="emitEvent('event1')"> </form> Within th ...

Retrieve the property values of `T` using a string key through the `in

Having trouble accessing a property in an object using a string index, where the interface is defined with in keyof. Consider the following code snippet: interface IFilm { name: string; author: string; } type IExtra<T extends {}> = { [i ...

The type 'void | Observable<User>' does not include the property 'subscribe'. Error code: ts(2339)

authenticate() { this.auth.authenticate(this.username, this.password).subscribe((_: any) => { this.router.navigateByUrl('dashboard', {replaceUrl: true}); }); } I'm puzzled by this error message, I've tried a few solu ...

Sending form data using an Ajax POST request to a Node/Express server

Greetings to those taking the time to read this. My current objective is to successfully implement a basic example of posting data to a node/express server. The post command functions from the ajax code, and express detects the request while sending a re ...

What steps can be taken to address an unusual conflict arising between a form post and an ajax post

One web page features the use of ajax for editing existing values. This is achieved by utilizing jQuery Inline Edit to post new data, update records, and return with success. The process works well initially. Subsequently, I implemented the functionality ...

Integrating TypeScript into an established create-react-app project

Struggling to integrate TypeScript into an existing create-react-app? I've always added it at the beginning of a project using create-react-app my-app --scripts-version=react-scripts-ts, but that's not working this time. The only "solution" I co ...

Ways to customize PreBid.js ad server targeting bidder settings

In an effort to implement a unique bidder setting key name within my prebid solution, I have taken the necessary steps as outlined in the documentation by including all 6 required keys. Is it possible to change the key name 'hb_pb' to 'zm_hb ...

Troubleshooting VueJS's Dilemma with Quotation Marks

When I try to parse a string containing either double quotes or single quotes, an error is being thrown: JSON Unexpected token. Is there a way to properly parse and bind it to a variable in Vue.js? PHP $arr = array(); $arr[0]['description'] = ...

What could be causing the net::ERR_CONNECTION_CLOSED error to occur following an ajax request?

I'm facing an issue where my code works perfectly fine on localhost, but I encounter the following error when trying to run it on a hosting platform: (failed) net::ERR_CONNECTION_CLOSED. Could someone please explain what this error signifies and p ...

Creating an HTML Form that Sends an Email

I'm completely stumped as to where the issue lies! The mail() function is working perfectly fine (I tested it with a simple PHP file), but for some reason, my form isn't sending any emails! HTML <section id="contact"> <div id="go ...

What is the best way to target a specific HTML element within a for loop in a Django template?

I need to create a button using JavaScript that can hide and display only the specific HTML elements within the same div. All these divs are part of a Django template loop, displaying different information. Currently, I'm using querySelector to select ...

Retrieve the JSON data from an AJAX request

I am a beginner in the world of AJAX and JavaScript. In one of my projects, I need to retrieve a JSON object in my JavaScript file. I have utilized spray-json library which displays the JSON object at this URL: http://localhost:8081/all-modules { "statu ...

How to utilize a prepared statement in MySQL using NodeJS for inserting or updating data in a specific table?

Below is the code snippet I need assistance with: connection.query({ sql: 'CREATE TABLE ? ( `wage` FLOAT NOT NULL , `monday` FLOAT NOT NULL , `tuesday` FLOAT NOT NULL , `wednesday` FLOAT NOT NULL , `thursday` FLOAT NOT NULL , `friday`) ENGINE = InnoDB ...

Transfer the text from one cell and insert it into the "neighbor" cell of a different column when the content is editable

present situation: Clicking on a row fills the entire row of another column, instead of just filling a single row. <p class="p-of-that" v-html="thatText" contenteditable @click="writeThat(myArr, $event)" ></p& ...

Using JQuery to duplicate text and insert it into a textarea

Looking for a more efficient way to achieve the same functionality with my JavaScript function. Currently, it copies text from a hidden span and inserts it into a textarea on a website after a few clicks. Any ideas on how to streamline this process? It&apo ...

What is the process for utilizing the JWT token on the front-end after obtaining it?

After hours of research, I am still struggling to implement login functionality using JWT Tokens. Here is my progress so far: My login API const loginUser = async (req, res, next) => { try { const {username, password} = req.body //g ...

JavaScript code to change an array into a stringified format

I have encountered a challenge with transforming an array. The original array looks like this: array = [ { "name": "name", "value": "Olá" }, { "name": "age" ...

Dragging the mouse outside of an element after clicking inside

I've come across a common issue, but unfortunately haven't been able to find a solution yet. window.onload = function (e) { var foo = document.getElementById('foo'); foo.addEventListener('click', function(e) { ...