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

Displaying dates on the Amcharts category axis for instances with empty data

I am currently creating a fruit consumption chart for each day, and so far everything is working correctly in the provided example. var chart = AmCharts.makeChart("chartdiv", { "type": "serial", "hideCredits": true, "fixedColumnWidth": '10px& ...

Working with Vue's v-for directive to bind computed properties

I am inputting a set of tasks into my v-form tasks: [ { title: 'title1', description: 'task 1 description', isComplete: functionA() }, { title: 'title2', ...

I am encountering an issue where the key is not located in the response array in PHP, causing my JavaScript chart to remain

Hey there! I'm currently working on a school project and could really use some assistance. The task at hand involves creating a web interface that can interact with an endpoint in order to: - Authenticate a registered user to retrieve an authenticati ...

Utilizing the <style scoped> feature within my Angular template

When adding CSS styles in the specified htm file's templateUrl while loading a directive, I wonder if this is a bad idea. Will it be repeated every time the template is instantiated on the rendered page, or does Angular handle this differently? By usi ...

Custom web addresses for files in the Vue 2.1 framework

After going through the documentation for Vue Router, it seemed like setting up redirects should be straightforward, but I'm having trouble making it work. My first attempt was to reference a file in S3: { path: '/rules', redirect: &ap ...

Refreshing the page results in a 404 error when utilizing React Router

I am currently facing an issue with my web application setup. Back-End My back-end consists of a Node.js/express server that serves files in response to specific requests made to certain routes. Front-End On the front-end, I have React pages that commu ...

Troubleshooting data binding problems when using an Array of Objects in MatTableDataSource within Angular

I am encountering an issue when trying to bind an array of objects data to a MatTableDataSource; the table displays empty results. I suspect there is a minor problem with data binding in my code snippet below. endPointsDataSource; endPointsLength; endP ...

The function URL.createObjectURL() is not recognized in Nuxt

Hey everyone, currently I'm utilizing Nuxt I have an image saved on the server as a blob that I want to display on the client side This is how my Component is structured: <template> <div class="product-page"> <div clas ...

Set a placeholder to display when Vuex has completed loading

How can I properly handle loading state after dispatching in Vue? Currently, when trying to set loading state to true before dispatch and false after, the following code does not work: this.loading = true; this.$store.dispatch('items', data); t ...

Intercepting HTTP requests on specific routes with Angular 4+ using an HTTP Interceptor

I've developed an HTTP_INTERCEPTOR that needs to function on certain routes while excluding others. Initially, it was included in the main app module file. However, after removing it from there and adding it to specific modules, the interceptor conti ...

Trouble loading CSS file in Vue library from npm package

When using vue-cli to build a library (npm package) that functions for both SSR and client-side, everything seems to be functioning correctly except for one issue; the CSS only loads if the component is present on the page being refreshed. However, when ac ...

Load various types of classes and run functions with matching names

I have encountered a challenging issue that needs to be resolved. Imagine having multiple classes located in a directory named services. These classes all include a constructor() and send() method. Examples of such classes can be Discord, Slack, SMS, etc. ...

What could be the reason for express-validator's inability to identify missing fields during the validation of XML input

My server, based on Express, is set up to parse XML instead of JSON using body-parser-xml. To validate the input body, I am using express-validator as shown in the following simplified example: router.post("/", body('session.credential[0].$.usern ...

The Step-by-Step Guide to Deselecting an Angular Checkbox with a Button

I currently have a situation where I have three checkboxes labeled as parent 1, parent 2, and parent 3. Initially, when the page loads, parent 1 and parent 3 are checked by default, while parent 2 is unchecked. However, when I manually check parent 2 and c ...

Refresh the content of a webpage in AngularJS without the need to fully reload the entire page

Within my controller and view files, I have content that is sourced from various places, including API calls. For instance, I have information retrieved from the database where users can update certain details like their last name. After submitting the up ...

Updating prop values within Vue JS using Alert component

I am utilizing VueStrap components that are based on the following link: Regrettably, I encounter an error when attempting to set the visibility for an alert within my code: HTML: <alert :show="showAlert" placement="top-right" :duration=3000 v-bind:t ...

Having trouble establishing a web socket connection using JavaScript

I'm experiencing an issue trying to connect my web socket to an Amazon instance using a specific IP address. I've had success connecting the web socket with a different IP and port using the Google Rest Client app, but now when I try to connect w ...

Should WordPress files be kept separate (php, css, and js) or combined into a single file?

Currently, I am updating my WordPress website with a goal of minimizing the number of plugins used. To achieve this, I prefer writing code only for essential functionalities. In order to optimize my work with php, css, and javascript files, I have been exp ...

Building a search form using Vue.js with query parameters

Incorporating Vue.js 2.6 with the vue-router component has been quite a journey for me. My search form setup looks like this: <form class="search-form" @submit.prevent="search"> <div class="form-group"> <input type="text" class= ...

Tips for generating an input element using JavaScript without the need for it to have the ":valid" attribute for styling with CSS

My simple input in HTML/CSS works perfectly, but when I tried to automate the process by writing a JavaScript function to create multiple inputs, I encountered an issue. The input created with JavaScript is already considered valid (from a CSS ":valid" sta ...