Is there a way to retrieve the selected value from a dropdown menu using vue.js?

I have a parent Vue component structured like this:

<template>
    <form>
        <div class="row">
            <div class="col-md-4">
                <form-select id="color" name="color" :data="color">Color</form-select>
            </div>
            <div class="col-md-4">
                <form-select id="size" name="size" :data="size">Size</form-select>
            </div>
        </div>
        ...
        <a href="javascript:" class="btn btn-danger" @click="add">
            Add
        </a>
    </form>
</template>

<script>
    import FormSelect from '../form/FormSelect.vue'
    export default {
        data(){
            return {
                quantity: [
                    {id: 1, value: '1'},
                    {id: 2, value: '2'},
                    {id: 3, value: '3'}
                ],
                size: [
                    {id: 1, value: 'S'},
                    {id: 2, value: 'M'},
                    {id: 3, value: 'L'}
                ]
            }
        },
        components: {FormSelect},
        methods: {
            add(event) {
                const color = document.getElementById('color').value,
                      size = document.getElementById('size').value
            }
        }
    }
</script>

Additionally, I have a child Vue component structured as follows:

<template>
    <div class="form-group">
        <label :for="id" class="control-label"></label>
        <select :id="id" :name="name" class="form-control" v-model="selected">
            <option v-for="item in data">{{item.value}}</option>
        </select>
    </div>
</template>

<script>
    export default {
        props: ['id', 'name', 'data'],
        data(){
            return {
                selected: ''
            }
        }
    }
</script>

Although I'm able to successfully get the selected values by clicking the "Add" button using JavaScript (document.getElementById), I want to transition to utilizing data binding within the Vue component structure. However, I am unsure of how to implement it.

Can anyone provide guidance on how to achieve this with data binding?

Answer №1

To transmit the event from a child component and send your data, utilize the on method to retrieve that data in the parent component:

Parent:

<form-select id="color" name="color" :data="color" v-on:triggerChange="changeColor">Color</form-select>

methods: {
 // ...
 changeColor(selected) {
   // Perform actions with the selected data
 }
 // ...
}

Child:

<select :id="id" :name="name" class="form-control" v-model="selected" v-on:change="applyColor">

methods: {
 // ...
 applyColor() {
   this.$emit('triggerChange',this.selected);
 }
 // ...
}

In response to your feedback, you can implement it like this:

this.$parent.$options.methods.someParentMethod(data)

Please note:

Exercise caution when using $parent and $children - they should be used as a last resort. It is recommended to prioritize prop and event usage for communication between parent and child components.

Answer №2

When embarking on the journey of developing new things, it is essential to ensure correctness every step of the way. The previous answer provided is not only accurate but also commendable for its timely delivery.

This additional explanation aims to dive deeper into the intricacies of developing applications in Vue, shedding light on important aspects such as:

A. Communication between parent and child components

B. Non Parent-Child Communication

A. Communication between parent and child components

  • Let's dissect the communication between parent and child components into manageable steps:

i) Establish a method X binding with the parent to listen to emitted messages from the child.

ii) Incorporate props property in the child component for data binding within the child.

iii) Utilize this.$emit to emit the same message (X) bound in the parent component.

Parent component

<template>
<form>
    <div class="row">
        <div class="col-md-4">
            <form-select id="color" name="color" (dropdownChanged)= 'colorChanged' :data="color">Color</form-select>
        </div>
        <div class="col-md-4">
            <form-select id="size" name="size" :data="size" (dropdownChanged)= 'sizeChanged'>Size</form-select>
        </div>
    </div>
    ...
    <a href="javascript:" class="btn btn-danger" @click="add">
        Add
    </a>
</form>
</template>

<script>
    import FormSelect from '../form/FormSelect.vue'
    export default {
        data(){
            return {
                quantity: [
                    {id: 1, value: '1'},
                    {id: 2, value: '2'},
                    {id: 3, value: '3'}
                ],
                size: [
                    {id: 1, value: 'S'},
                    {id: 2, value: 'M'},
                    {id: 3, value: 'L'}
                ]
            }
        },
        components: {FormSelect},
        methods: {
            add(event) {
                const color = document.getElementById('color').value,
                      size = document.getElementById('size').value
            },
            colorChanged(color) {
               console.log('Color Changed', color);
            },
            sizeChanged(size) {
               console.log('size Changed', color);
            },
        }
    }
</script>

Child Component

<template>
    <div class="form-group">
        <label :for="id" class="control-label"></label>
        <select (change)='dropdownChanged' :id="id" :name="name" class="form-control" v-model="selected">
            <option v-for="item in data">{{item.value}}</option>
        </select>
    </div>
</template>

<script>
    export default {
        props: ['id', 'name', 'data'],
        data(){
            return {
                selected: ''
            }
        },
       methods: {
         dropdownChanged() {
           this.$emit('changesOccured',this.selected)
         }
       }
    }
</script>

B. Non Parent-Child Communication

Sometimes, when two components need to communicate without being parent and child, using an empty Vue instance as a central event bus can be a solution:

var bus = new Vue()
// in component A's method
bus.$emit('id-selected', 1)
// in component B's created hook
bus.$on('id-selected', function (id) {
  // ...
})

For more information, visit: https://v2.vuejs.org/v2/guide/components.html

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

Calculate the total length of the nested arrays within an object

Check out this object: const obj = { name: "abc", arr: [{ key1: "value1", arr1: [1, 2, 3] }, { key1: "value2", arr1: [4, 5, 6] }] } I'm looking to find a way to quickly calculate the sum of lengths of arrays arr1 and arr2. ...

Jerky visuals on the canvas

My canvas animation runs smoothly in Chrome, but it's as choppy as a bad haircut in Firefox. Surprisingly, the code is not even that complex. Is there anything in my code that could be causing this slowdown? Here is the jsfiddle link for reference: h ...

Deactivate form fields when entering data into a set of interconnected fields

I need help with the following functionality using jQuery on the form below: 1/ If any character is entered in 'filter_loan_id', 'filter_fname', 'filter_lname', or 'filter_postcode' fields, then disable the 'fi ...

What is the best way to immediately update the state in a React functional component?

Having recently started learning React, I find myself struggling to understand the lifecycle of a functional component. Let's consider a scenario where I have multiple checkboxes labeled as: checkbox, a, b, c, and d, each corresponding to values a, b, ...

Utilizing Async / Await in the created lifecycle hook - Vue2

I recently installed the vue-element-loading package and added its component to my page.vue: <vue-element-loading :active="isActive" :is-full-screen="true"/> After adding a variable to my data: data () { return { isActive: false, } } I th ...

Safari browser is experiencing issues with the custom file upload script

My custom upload script allows users to easily select images for upload by clicking or dragging them into the designated box. A preview of the chosen image should appear, and this functionality works smoothly in Firefox and Chrome. However, I've encou ...

Using a JSON string with form field names and corresponding values to automatically fill in form fields using jQuery

My JSON string looks like this: [{"meta_key":"algemeen_reden","meta_value":"oplevering"},{"meta_key":"algemeen_netspanning","meta_value":"230"}] Currently, I am using the following script to fill out form fields: // Grab Algemeen Data get_algemeen_data ...

Concentrate and select non-interactive elements with your mouse

Is it possible to set tab index on non-form elements like the div tag? I tried using tab index, but when the div is focused and the enter button is tapped, the ng-click event associated with the div tag is not triggered. <div tabindex="0" role="butto ...

The request for an advertisement was successful, however, no ad could be displayed as there was insufficient ad inventory available. Please handle the situation appropriately with the

Using react-native, I am trying to incorporate ads into my app but encountering an error. Despite attempting various solutions, nothing seems to work. It appears that the issue may lie with the AdMob Android SDK. While I have reviewed SDK videos related to ...

React-Native introduces a new container powered by VirtualizedList

Upon updating to react-native 0.61, a plethora of warnings have started appearing: There are VirtualizedLists nested inside plain ScrollViews with the same orientation - it's recommended to avoid this and use another VirtualizedList-backed container ...

Retrieve JSON data with Vue.js prior to rendering the page

I have a query about extracting JSON data objects and rendering them prior to mounting. Just to clarify, I am working in a standalone environment. I don't believe the issue lies with the function itself, but rather with the lifecycle aspect of it. I h ...

Utilizing the Kraken.com API to create a message signature with AngularJS

I'm currently tackling Angular2 and for my first project, I want to tap into the Kraken.com API. (I know, I could have chosen an easier task :) The "Public" calls are working smoothly, but I've hit a snag with the "Private" methods. (Those requi ...

Guide on how to receive multiple responses from a single ajax request in PHP

I am in the process of developing a web application that includes a search feature. When a user enters a name to search for, I use an AJAX request to retrieve and display records related to that specific person. However, due to the extensive amount of info ...

Error message: Cypress Vue component test fails due to the inability to import the Ref type (export named 'Ref' is missing)

Recently, I created a Cypress component test for my Vue component by mounting it and verifying its existence. The component utilizes Vue's Ref type and is structured as a TypeScript component. However, during the test execution, Cypress encountered a ...

Tips for eliminating the domain name from the src URL attribute using Jquery

Is there a way to extract the img src attribute and retrieve only the image path without the domain name included? var imgurl = "http://nitseditor.dev/img/home/bg.jpg"; For instance, I would like to display img/home/bg.jpg instead of the full URL. Any id ...

Issue with Vuex functionality not functioning within a child component

I've been struggling with this simple code that is causing me a lot of frustration. Both some-component and the root instance are logging errors to the console instead of binding from the vuex object. What could I possibly be overlooking here? var ...

The state change in React-Redux does not trigger a re-render

I successfully developed a large react-redux application with an undo feature in one component. While the state updates properly and re-renders the component along with its children, I noticed that the component's position on the page remains unchange ...

Is it feasible to create a doughnut chart with curved edges?

My goal is to create a doughnut chart, but my search for reliable CSS/SVG/Canvas solutions has not been successful. https://i.sstatic.net/Rq6Lx.jpg I want each segment to have fully rounded corners, which presents a unique challenge. ...

Iframe form submissions

I am interested in accomplishing the following task. My objective is to submit a form to my booking engine and show the results on either a new page or within a Div element. Ideally, when the user clicks the submit button, it would display an Iframe or re ...

What are the steps to recursively transform a JavaScript object?

I am currently working on recursively transforming a JavaScript object, but I have encountered an issue. The problem is: if any object key has exactly two properties - 'label' and 'value', then the value should change to the label only ...