The value on the input of a custom Vue component does not update as expected when using v

I'm currently working on a custom component called customCombobox. It functions similarly to a regular v-combobox, but with an added feature - after the user presses the tab key, it automatically selects the first option available.

Everything in my implementation seems to be functioning correctly, except for the fact that the v-model on this field is consistently returning as null.

<template>
  <v-combobox ref="combobox" :rules="rules"
              @keydown.tab.prevent="selectFirst"
              :value="innerValue" :label="label"
              :items="items"

  >

  </v-combobox>
</template>
<script>
module.exports = {
  props: ['value', 'label', 'items', 'rules'],
  data() {
    return {
      innerValue:null,
    }
  },
  watch:{
    value(_new){
       this.innerValue = _new
      this.$emit('input',[_new])
      this.$emit('change')
    }
  },
  methods: {
    selectFirst() {
      var combobox = this.$refs.combobox
      var filteredItems = combobox.filteredItems
      if (filteredItems.length){
          this.innerValue = filteredItems[0]
      }
    }
  },
  computed: {

  }
}
</script>

Any idea what might be causing this issue?

Answer №1

To handle the v-model from the parent and pass it to its child v-combobox, you can implement a computed setter in the custom component:

Custom component:

<v-combobox v-model="selected" v-bind="$attrs"></v-combobox>
computed: {
  selected: {
    get() {
      return this.value;
    },
    set(val) {
      this.$emit('input', val);
    }
  }
}

By using v-bind="$attrs", all props from the parent are also passed down. Check out this demo:

Vue.component('comp', {
  props: ['value'],
    template: `
    <v-combobox v-model="selected" v-bind="$attrs"></v-combobox>
  `,
  computed: {
    selected: {
      get() {
        return this.value;
      },
      set(val) {
        this.$emit('input', val);
      }
    }
  }
})

new Vue({
  el: '#app',
  vuetify: new Vuetify(),
  data() {
    return {
      selected: 'Vue',
      label: 'This is my label',
      rules: ['These are my rules'],
      items: ['Programming', 'Design', 'Vue', 'Vuetify']
    }
  }
})
#app {
  padding: 48px;
}
<div id="app">
  <v-app id="inspire">
    Selected in parent: {{ selected }}
    <comp
         v-model="selected"
         :label="label"
         :items="items"></comp>
  </v-app> 
</div>

<link href="https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/@mdi/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1a7c75746e5a2e3462">[email protected]</a>/css/materialdesignicons.min.css" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="304645554459564970021e48">[email protected]</a>/dist/vuetify.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7d0b08183d4f5305">[email protected]</a>/dist/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="89fffcecfde0eff0c9bba7f1">[email protected]</a>/dist/vuetify.js"></script>

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

Utilizing Laravel's URL::asset method in conjunction with a JavaScript variable

Having a go at creating an HTML tag using the Jquery snippet below $("<option />",{ 'data-src':"{{ asset(my-javascript-variable) }}", id:'my_id').appendTo($('#image')); An option tag is being added to a select element. ...

Sending an array object from Ajax to Django Framework

AJAX Script Explanation: Let's consider the variable arry1D contains values [0,1,2,3,4] $.ajax({ url: "{% url 'form_post' %}", type: "POST", data: { arry1D: arry1D, 'csrfmiddlewaretoken': tk }, ...

What is the correct way to have Material-UI's <TextField/> component return with a ref attribute, similar to <input/> in ReactJS?

Using this particular method: handleClick(event) { const inputText = this.refs.inputText console.log(inputText.value.trim()) } I am attempting to make Material-UI's <TextField/> return the input text accurately with a ref, similar ...

Showing a variety of pictures within a specified time frame

In my CSS, I have defined classes that allow me to display different background images on a page at set intervals: .image-fader { width: 300px; height: 300px; } .image-fader img { position: absolute; top: 0px; left: 0px; animation-name: imagefade; ...

How does the use of let versus const differ when iterating through a collection?

Utilizing Node.js (ES6) to iterate through each item in a collection like the one provided below: var statuses = [{ statusId: 1, description: 'New' }, { statusId: 2, description: 'Pending' }, { ...

Experiencing a Typescript issue while trying to set a string as the state of a React component with a specified TS type

I've defined a state in my React component for a specific data type called Color. \\ state const [messageSeverity, setMessageSeverity] = useState<Color>('success'); \\ TS type export type Color = 'success&ap ...

Centralizing images in a Facebook gallery/lightbox during the loading process

Is the image width and height stored in Facebook's gallery database? In typical JavaScript usage, the image width and height cannot be determined until the image is fully loaded. However, on Facebook, images are pre-loaded before being displayed, ens ...

error: encountering issue with Vue TypeScript Jest tests - '$store' property is undefined

I've been facing issues with my tests failing after a recent npm install. I've tried adjusting versions up and down, but haven't had any success. Interestingly, the $store isn't directly used in any of the components or tests. Despit ...

Attempting to perform recursion on two functions simultaneously may result in one of the functions being undefined

There is a page on my site that clients tend to keep open for long periods of time without refreshing, sometimes over 24 hours. Some of the actions on this page require a valid PHP session, so I created a simple set of functions to check this every 10 minu ...

When the browser is not in the foreground, clicking on the Bootstrap datepicker with Selenium does not register

When you click on the input field <input id="dp1" class="span2" type="text" value="02-16-2012"> If the browser is in the background, the datepicker popup will not display. Even using javascript or jquery to click the input field does not show the ...

The method .setArray has been deprecated in THREE.BufferAttribute. Instead, please use BufferGeometry .setAttribute for unindexed BufferGeometry operations

Seeking assistance with updating the webgl-wireframes library code to the latest version of threejs. The current function is generating the following errors: Uncaught TypeError: THREE.Geometry is not a constructor THREE.BufferAttribute: .setArray has ...

Check if the DIV element does not exist in the DOM before using the

I have been working on a large project and what I need is if div 1 does not contain div 2 as a child{ div1.appendChild(div2) } However, I am facing difficulties in solving this issue Here is my code snippet <script> dc = document.createElement( ...

The width of the table remains consistent

I have created a division that includes two tables stacked on top of each other. However, I am facing an issue where the width of the second table remains fixed and does not change even when I try to increase it. Here is the code snippet below: functio ...

Navigate to the date selector and select the following month

https://i.sstatic.net/AdWVs.png <button class="mat-calendar-next-button mat-icon-button" mat-icon-button="" type="button" ng-reflect-disabled="false" aria-label="Next month"><span class="mat-button-wrapper"></span><di ...

What is the best way to create an answer label box that validates your response?

I am looking to design a question box label that resembles a search box. In this unique setup, users will have the option to input their answer into the question label. For example, if the user types 'kfuffle' as the answer, they will automatical ...

Is Bootstrap compatible with Vue3 or is it specifically designed for use with Vue2?

Curious about the compatibility of bootstrap with vue3? Debating whether to transition to vue 3 or stick with vue 2? ...

Toggling a div updates the content of a different div

I am looking to make the content within <div class="tcw-content"> dynamically change when a different div is clicked. I have little experience with Ajax, so I'm wondering if there are alternative ways to accomplish this using JS/CSS. If anyone h ...

Determining the size of a custom-typed array in Typescript

Can anyone explain how to find the length of a custom typed array? For example: type TMyArray = IProduct[] interface IProduct { cost: number, name: string, weight: number } So, how can we determine the length in this case: const testArr: TMyArray ...

Update the image within the svg tag

I am attempting to modify a preexisting SVG element within an HTML document. Here is the current code: <svg class="logo" viewBox="0 0 435 67"> <!-- IMAGE DIMENSIONS --> <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#logo- ...

When the enter key is pressed, the form will be submitted and the results will be displayed in a modal window without

Behold, my unique form! It lacks the traditional <form></form> tags. <input id="query" name="query" style="font-size: 18pt" id="text" data-email="required" type="text" placeholder="Search Here from <?php echo $row['no']."+"; ?& ...