Tips for implementing controlled components in Vue to update values in the parent component object

Utilizing controlled components, I am able to emit the selected value. For example,

// app-select.vue

<v-select :items="[1,2,3]"  @change="$emit('input', $event)"></v-select>

// parent-component.vue

<app-select v-model="selectedValue" />

When the value of v-select is changed, it updates selectedValue on the parent component.

Now, what if I have an object that needs to be updated by a controlled component with multiple selectors:

parent-comp.vue

<template>
  <filter-comp> v-model="filterObj"</filter-comp>
</template>
<script>
  import FilterComp from './filtercomp'
  export default {
    components: {
      FilterComp
    },
    data () {
      return {
         filterObj: {}
      }
    }
  }
</script>

And a child component with input fields capable of emitting values:

<template>
   <v-select :items="filterOneItems" @change="$emit('input', $event)">></v-select>
   <v-select :items="filterTwoItems" @change="$emit('input', $event)">></v-select>
</template>

The objective is to update the parent component when there's an input on v-select like this:

filterObj: {
   filterOne: 'value 1',
   filterTwo: 'value 2'
}

Is there a way to achieve this functionality?

Answer №1

Consider these two approaches to address the issue. Firstly, utilize prop instead of two-way binding:

In parent-comp.vue

<filter-comp :obj="filterObj"></filter-comp>

And in filter-comp.vue

<template>
  <div>
    <v-select :items="items" v-model="obj.filterOne"></v-select>
    <v-select :items="items" v-model="obj.filterTwo"></v-select>
  </div>
</template>
...
  props: {
    obj: {
      type: Object,
      default: {}
    }
...

JSFiddle link

Secondly, implement v-model as indicated below:

In filter-comp.vue

<template>
  <div>
    <v-select :items="items" @change="change('filterOne', $event)"></v-select>
    <v-select :items="items" @change="change('filterTwo', $event)"></v-select>
  </div>
</template>
...
  methods: {
    change(name, value) {
      this.$emit('input', {
        ...this.value,
        [name]: value
      })
    }
...

JSFiddle link

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 Ajax for validation on Telerik Kendo Grid with Change Event

I am working with a Telerik Kendo Grid that has a column listing medical diagnoses. The list is populated using a method in the controller. My task is to verify whether a newly added diagnosis is already present in the grid, and only allow adding diagnoses ...

I'd like to know how to retrieve the start and end dates of a specific month using JavaScript

How can I retrieve the start and end date of the current month? const currentDate = new Date(); const startOfMonth = new Date(currentDate.getFullYear(), currentDate.getMonth(), 1); const endOfMonth = new Date(currentDate.getFullYear(), currentD ...

Attempting to generate a JSON array using JavaScript

As I embark on my journey to learn JSON, I've encountered an issue while attempting to create an array of object Messages. The declaration seems to be error-free, but when I try to access it using the code snippet below: serverReply2.Mesages[0].Date, ...

Trouble with sending arguments to Express middleware

I'm currently working on developing a custom input validation middleware using Express. My aim is to create a middleware that takes 2 parameters in order to validate client input effectively. Despite referencing various sources, including the Express ...

Tips for adjusting column sizes in react-mui's DataGrid based on screen size

I would like the title column to occupy 3/4 of the full row width and the amount column to take up 1/4 of the full row width on all screens sizes (md, sx...). Here is the updated code snippet: import React from 'react' const MyComponent = () =&g ...

Concealing the rear navigation button within the material carousel

I have a material css carousel, and I am trying to hide the back button on the first slide. I attempted to use the code below from a previous post The following code snippet prevents the user from looping through the carousel indefinitely. Stop looping i ...

Retrieve the chosen selection from a dropdown menu using AngularJS and Ionic

I've been encountering some issues with the select feature in AngularJS. Despite searching extensively for solutions, none seem to be working for me. The JSON structure I'm dealing with is generated from my service.php: [ { "Name": ...

Search in the Firestore database for documents that have a field containing a reference to another document. Once those results are found, use the reference to conduct a second query

In an attempt to optimize the query that delivers details of all events a participant has attended, I have restructured my database schema. Events with participants are now linked through a subEvent subcollection in the users collection, storing document r ...

Vercel and Firebase Realtime Database causing snapshot.val() to return null during build deployment

Creating a blog application using Next.js, Firebase Realtime Database, and Vercel for hosting has been seamless on my local machine. Even after running npm run build, everything functions perfectly. However, when deployed to Netlify in production, the snap ...

Getting the http response content of a Slim PHP API with Angular JS: A step-by-step guide

My Slim PHP programmed API sends JSON responses in the following format: $response['some-text'] = 'blabla'; $app->response->setStatus(200); $app->response()->headers->set('Content-Type', 'application/json& ...

Can you tell me the distinction between using RemoteWebDriver's executeScript() and Selenium's getEval() for executing

Can you explain the distinction between these two pieces of code: RemoteWebDriver driver = new FirefoxDriver(); Object result = driver.executeScript("somefunction();"); and this: RemoteWebDriver driver = new FirefoxDriver(); Selenium seleniumDriver = ne ...

The npm package installation process encountered difficulties in accessing the Chart.Js library

Currently, I am in the process of developing a web application that tracks and logs hours spent on various skills or activities. The data is then presented to the user through a bar graph created using Chart.js. Initially, I was able to display a mock grap ...

What are some ways to enhance the loading time of my PHP-powered website?

Having troubles with my PHP-driven website that showcases real-time stock market data due to slow loading speeds. The site utilizes PHP for scraping financial information from external sources and presenting it on the front end. However, the performance is ...

Is the exchange between Ajax/jQuery and PHP a two-way street?

My jQuery ajax call looks like this: $.ajax({ type: "POST", url: ajaxurl, data: data, success: function(response){ alert(response); } }); I am retrieving data from PHP using the following code: $data_array = get_data(); forea ...

Checking for the Existence of a Database Table in HTML5 Local Storage

Upon each visit to my page, I automatically generate a few local database tables if they do not already exist. Subsequently, I retrieve records from the Actual Database and insert them into these newly created local tables. I am wondering if there is a me ...

``The modification of an input value after it has been initially

I find myself in a perplexing situation where I am setting a value to an input element from a route parameter. <input type="search" class="form-control search-control" :value="search"> Below is the search computed function: computed: { search() ...

Importing JWT in ES6SyntaxCreating ES6 imports

I'm currently developing a nodeJS web application and utilizing JWT for authentication. My code is all written in ES6 modules, so I wanted to import JWT the same way. However, it seems that the package does not fully support this method yet. Since I&a ...

Is it possible to reference a .js file within an HTML file using AngularJS?

Having a slight issue with an email function. I experimented with the 'nodemailer' package and successfully sent an email when coding in a .js file. Upon calling the .js file (node emailfile.js), the email was received as expected (code provided ...

Having difficulty accessing POST data through $.ajax request

I am currently working on a simple JavaScript code that is set up to send POST requests to my local server. The JavaScript and PHP files are both located on localhost, so I don't have to worry about any cross-site issues for now. Here is the JavaScrip ...

Populate an HTML5 arc with an image - Leveraging the power of HTML5 Canvas

I'm working with an HTML5 Canvas (JSFiddle) that currently displays circles created using the following function: function createball(x,y,r,color){ context.beginPath(); context.arc(x,y,r,0,Math.PI*2,true); context.fillStyle = color; c ...