Getting the select value from a Vue component and sending it back to the parent component

I am struggling with this issue. I have a component called StockSearch.vue, and within it, there is another component named StockSearchSelect.vue. The code snippet is provided below.

My objective is to update the selected value within the makes object in StockSearch whenever the selected option changes in the StockSerchSelect component. How can I achieve this?

StockSearch.vue

<template>

    <div class="flex flex-col lg:flex-row">
        <search-select title="Make" :options="data.makes"></search-select>
        <search-select title="Model" :options="data.makes"></search-select>
        <search-select title="Variant" :options="data.makes"></search-select>
        <search-select title="Trim" :options="data.makes"></search-select>
        <search-select title="Bodystyle" :options="data.makes"></search-select>
        <search-select title="Transmission" :options="data.makes"></search-select>
        <search-select title="Doors" :options="data.makes"></search-select>      
    </div>

</template>
<script>
import SearchSelect from './StockSearchSelect';
export default {
    components: {
        SearchSelect
    },
    data: function() {
        return {
            data: {
                makes: {
                    options: [
                        { code: 1, display: 'Audi' },
                        { code: 2, display: 'BMW' },
                        { code: 3, display: 'Chevrolet' },
                        { code: 4, display: 'Mercedes Benz' },
                        { code: 5, display: 'Suzuki' },
                        { code: 6, display: 'Volvo' },
                        { code: 7, display: 'Lamborghini' },
                        { code: 8, display: 'Citron' },
                        { code: 9, display: 'Jeep' },
                    ],
                    selected: null
                }
            }
        }
    },
    watch: {
        data: {
            deep: true,
            handler: function(data) {
                console.log(data);

            }
        }
    }
}
</script>

StockSearchSelect.vue

<template>
    <div class="w-full p-2">
        <label class="block uppercase tracking-wide text-gray-700 text-xs font-bold mb-2" for="grid-state">{{ title }}</label>
        <div class="relative">
            <select class="block appearance-none w-full bg-gray-200 border border-gray-200 text-gray-700 py-3 px-4 pr-8 rounded leading-tight focus:outline-none focus:bg-white focus:border-gray-500" id="grid-state" v-model="selected">
                <option value="">Any {{ title }}</option>
                <option v-for="(value, index) in data.options" :key="index" :value="value.code">{{ value.display }}</option>
            </select>
            <div class="pointer-events-none absolute inset-y-0 right-0 flex items-center px-2 text-gray-700">
                <svg class="fill-current h-4 w-4" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20"><path d="M9.293 12.95l.707.707L15.657 8l-1.414-1.414L10 10.828 5.757 6.586 4.343 8z"/></svg>
            </div>
        </div>
    </div>
</template>
<script>
export default {
    props: {
        title: String,
        options: Array,
        selected: Int
    },
    data: function() {
        return {
            selected: null
        }
    },
    watch: {
        selected: function(value) {

        }
    }
}
</script>

Answer №1

To update the makes object only when an option is changed, simply emit an event when the value changes and then listen for the event in the parent component. It's recommended to go through the documentation on props and custom events.

You can modify the select code below by adding

@input='$emit("selected", $event.target.value)'

<select class="block appearance-none w-full bg-gray-200 border border-gray-200 text-gray-700 py-3 px-4 pr-8 rounded leading-tight focus:outline-none focus:bg-white focus:border-gray-500" id="grid-state" v-model="selected" @input='$emit("selected", $event.target.value)'>
    <option value="">Any {{ title }}</option>
    <option v-for="(value, index) in data.options" :key="index" :value="value.code">{{ value.display }}</option>
</select>

Then, include

@selected="data.makes.selected = $event"
in the below component.

<search-select title="Doors" :options="data.makes" @selected="data.makes.selected = $event"></search-select>      

A functional snippet for reference is added below.

Vue.component("my-select", {
  template: "<select @input='$emit(`selected`, $event.target.value)'><option selected>Please Select</option><option value='1'>1</option><option value='2'>2</option></select>"
});

new Vue({
  el: "#app",
  data: () => {
    return {
      selectedValue: null
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <div>
    <my-select @selected="selectedValue = $event"></my-select>
    {{selectedValue}}
  </div>
</div>

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

Guide on mocking a function inside another function imported from a module with TypeScript and Jest

I have a function inside the action directory that I want to test: import { Action, ActionProgress, ActionStatus, MagicLinkProgress } from '../../interfaces' import { areSameActions } from '../actionsProgress' export const findActionPr ...

"Exploring the world of coding with pattern numbers and loops in

I am attempting to use JavaScript code to generate a specific pattern. To do this, I would like the user to input the following parameters: For instance, the starting number: 2 Insert the final number: 5 Enter the jump: 2 So far I have tried the followi ...

Stop event bubbling in Vue.js for router link

I'm working with the following HTML template... <template> <li class="nav-item" style="z-index:9"> <router-link :to="link.path" @click.native="linkClick" ...

Highlight all the written content within the text box

I'm struggling with a piece of code that is supposed to select all the text inside an input field: <input id="userName" class="form-control" type="text" name="enteredUserName" data-ng-show="vm.userNameDisplayed()" data-ng-model="vm.enteredUs ...

How to utilize map, reduce, and filter methods in JavaScript to print values from a nested array

The end goal is to have a unique entry for each name in the provided array. (Similar to the commented rows at the bottom of the snippet below) If there are identical names, only keep the entry with the highest count. In case of duplicate counts, choose th ...

What do you prefer: defining properties with the JSON object or with objectName.property in JavaScript

Can you tell me which approach is considered the best practice? Is it better to use the "this" statement in the following way: var obj = { x: 20, y: 10, width: this.x, height: this.y, render: function () { // renders object on canvas ctx.fi ...

Encountered an error trying to access the length property of an undefined variable while passing props

I need help with my shopping app project. I am trying to create a feature where if the cart is empty, it should display a message saying "shopping cart is empty." However, when I try to implement this, I keep getting a type error that says "Cannot read p ...

How to link a JavaScript file within a PHP document

I have an HTML file (index.html) that is using JavaScript to call a PHP file (pdj.php) and display the output in a div (pdj), which is functioning correctly. $.ajax({ url: '../command/pdj.php', type: "POST", data: ({xparam: xpara ...

How can you deduce the type from a different property in Typescript?

I have encountered obstacles in my development process and need assistance overcoming them. Currently, I am trying to configure TObject.props to only accept 'href' or 'download' if the condition TObject.name = 'a' is met, and ...

Is it possible to enlarge a webpage programmatically similar to how it is done in browsers like Internet Explorer or Firefox?

Here's a simple scenario - my layout is 800 by 600. When I press Ctrl and +, it zooms in and looks great. I'm curious if there's a way to achieve the same effect using CSS or Javascript? Ideally, I want it to happen automatically without th ...

Tips for avoiding unnecessary re-renders

The component I created sends props to both the checkbox and range components. During testing, I noticed that when a change was made in the range component, the checkbox also re-rendered even though it wasn't changed, and vice versa. Issue: When ...

Is it feasible to arrange <DIV>s based on their dates?

I encountered an issue while working with an ordering function. var $wrapper = $('#list'); $wrapper.find('.blogboxes').sort(function (a, b) { return +b.dataset.date - +a.dataset.date; }) .appendTo( $wrapper ); <script src="ht ...

Having trouble retrieving coordinates from the ajax request and passing them to the Google Maps script

In my places.php file, I am retrieving coordinates from the database and confirming their accuracy through echoing. The connection to the database is established without any issues. A self-executing function has been created in order to continuously update ...

Creating a Form with Dynamic HTML when Button is Clicked

I have been working on enhancing the functionality of my website app located at , but unfortunately, I have not been successful so far. My goal is to introduce a vendor information form with just one click of a button and then enable users to add products ...

What is the best way to redirect to a different URL in angular after signing in with AWS Amplify?

Currently, I am utilizing the latest authentication component from AWS-Amplify. While I can successfully log in, I am facing an issue where the URL remains the same after logging in, instead of redirecting to a custom URL as desired. To provide some contex ...

jQuery UI's $(...).sortable function is throwing an error when being used with WebPack

After setting up everything correctly, I encountered an unusual issue with Webpack. Let's take a look at this simple app.ts file: 'use strict'; import $ = require('jquery'); import 'jquery-ui'; $(function() { $( " ...

Utilize AJAX to retrieve an array from a PHP database query

My current objective is to retrieve an array from a PHP file that queries a database and store the results in that array. However, I am facing issues with making AJAX work as I am unfamiliar with its implementation. Below is my PHP code snippet: $mysqli ...

Issue with Storefront UI - SfComponentSelect functionality not functioning correctly

I have implemented the SfComponentSelect in my custom component, as shown in the official documentation. However, when I select an option from the dropdown, the selected option does not appear above the label "MySelect", unlike the example provided in the ...

Tips for optimizing Angular source code to render HTML for better SEO performance

Our web platform utilizes Angular JS for the front-end and node js for the backend, creating dynamic pages. When inspecting the code by viewing the source, it appears like this: For our business to succeed, our website needs to be SEO-friendly in order to ...

Building an Angular form that is reactive and dynamically populates fields from an array

I am currently working with Angular 9 and I am facing a challenge in implementing a component that utilizes reactive forms. Below is a snippet of my code: approval-edit.component.ts public nominationAllOf: NominationAllOf[]; public approvalEditForm: Form ...