Guide on connecting state from a higher-level component to a reusable selectInput component in Vue 3

I have a component named ChooseColor.vue that requires an array of color options for the selection input. The parent component where this ChooseColor component is included holds the user's information, specifically the favorite color property. How can I establish a binding for this in Vue?

UserSelection.vue

<script setup>
    import { ref } from 'vue';
    import ChooseColor from './ChooseColor.vue';

    const user = ref({
        name: '',
        favoriteColor: '',
    })

    const colorOptions = ref(['red', 'green', 'blue', 'white', 'black'])

</script>

<template>
    <div class="user-selection-container">
        <div class="user-selection">
            <p>Favorite Color:</p>
            <ChooseColor :colorOptions="colorOptions" />
        </div>
    </div>
</template>

ChooseColor.vue

<script setup>
    defineProps({
        selectOptions: Array,
    })
</script>

<template>
    <select>
        <option disabled value="">Please choose one</option>
        <option v-for="colorOption in colorOptions" v-bind:key="colorOption">{{ colorOption }}</option>
    </select>
</template>

Answer №1

Utilize v-model to handle data binding in Vue.js. Set your ref value to v-model, and then the child component must receive it as a prop and emit any changes back to the parent.

Parent Component

<SelectInput v-model="user.favoriteColor" />

Child Component

<select :value="modelValue" @change="updateModel">
defineProps({ modelValue: String })
const emit = defineEmits(['update:modelValue'])

function updateModel(e) {
    emit('update:modelValue', e.target.value)
}

Vue Playground example

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

Effectively handle multiple connections from nodejs to postgres using the pg library

I need to run a script that performs multiple queries using the pg library for managing connections. However, I am facing an issue where my program stops working when the connection pool is full and does not queue future queries. I have tried setting the p ...

Encountering difficulty in adding content to a table using JavaScript. An error message appears stating that assignment to a function

I am utilizing ajax to retrieve an item from a web API, and then attempting to allocate attributes of that item to a table: function find() { var id = $('#contentID').val(); $.getJSON(uri + '/' + id) .done( ...

Is this code correct for passing a variable to another form?

$("#delete").click(function() { deleterecord(); }); function deleterecord(){ var id = $("#iduser").val(); alert("aw"+id); var id = $('#iduser').attr(); e.preventDefault(); pressed = "delete" $.ajax({ ...

How to troubleshoot window.location not functioning in PHP, JavaScript, and

There is a software that utilizes Ajax Get. However, the code provided below seems to be malfunctioning. What steps can I take to rectify this issue? Javascript snippet: <script> function purchase_item(itemID) { $.ajax({ ...

What is the best way to remove double quotes surrounding "name" and "count" when displayed in the JavaScript console output?

I am struggling to transform the input: ["apple", "banana", "carrot", "durian", "eggplant", "apple", "carrot"] into the desired output: [{ name: "Apple", count: 2 }, { name: ...

Building a like/dislike feature in Angular

Here is a snippet of code I have that includes like and dislike buttons with font-awesome icons: <ng-container *ngFor="let answer of question.answers"> <p class="answers">{{answer.text}} <i class="fa fa-hand-o-le ...

Utilizing Ajax to dynamically submit specific form fields

I'm just starting out with Jquery ajax, and I'm experimenting with submitting specific fields for validation instead of the entire form. I've created a function to check if a username is available, and it's working well. However, I want ...

Placing elements from an array into a customized output

Currently, I am dealing with a unique output: dAmn_Raw('send chat:Sandbox\n\nmsg main\n\nthismessage'); In my code, there exists a variable: myvariable that stores a random value selected from an array I formulated. The cha ...

What is the best method for securely storing and managing refresh and access tokens within a node.js application?

Currently, I am working with next.js and I am looking for a way to persist an API refresh token without using a database in my application. What would be the recommended practice for storing this token securely so that it can be updated as needed? Storin ...

Is there a way to modify my code to eliminate the need for a script for each individual record?

Whenever I need to create a code with the ID by browsing through my records, is there a way to make just one function for all the records? $tbody .= '<script> $(document).ready(function(){ $("#img'.$idImage .'").click(functi ...

The inverse function for Ember Handlebars helper options is experiencing an undefined error

With a template in hand, I needed to toggle the display of certain text based on a method's return value. Research led me to the recommendation of using handlebars helpers for this purpose. So, I implemented a resetPassword helper within the controlle ...

Make sure to use dispatch when updating the array to prevent any potential infinite loops

I am currently working with JSX to create a function that reads user profiles and updates them upon clicking a button. The object userProfiles contains existing user profile data, which should be updated by combining the current contents with those from ne ...

Issues with Three.js materials not rendering properly when loading .obj and .mtl files

I recently downloaded a free 3D model and I'm attempting to view it using three.js. Although the model is loading correctly, there seems to be an issue with the materials not loading properly. Strangely enough, only the wine bottles behind the bar are ...

The beforeDestroy lifecycle hook for a Nuxt page component

Before moving to a specific page, I must emit some events. My current approach is using the beforeDestroy hook for this purpose. However, it seems that the method is not being triggered. // pages/view.vue beforeDestroy() { this.$alertEvent('finishe ...

Sending data from a bespoke server to components within NextJS

My custom server in NextJS is set up as outlined here for personalized routing. server.js: app.prepare() .then(() => { createServer((req, res) => { const parsedUrl = parse(req.url, true) const { pathname, query } = parsedUrl ...

JavaScript - Functions in objects losing reference to previously created object properties

Having trouble with my Candy function. When I create an object of the Candy function, all attributes are created correctly. However, when I try to run the draw function, it always uses the properties of the second object created instead of the one I want. ...

Issues persist with jQuery ajax request attempting to retrieve data from database

I attempted to retrieve data from my database using jQuery AJAX. Below is the code snippet I used: <script> $(document).ready(function(){ function fetch_data(){ $.ajax({ type:"POST", url:"http://localhost:88/phpPoint/select.php", success:function(re ...

Error message when converting obj to js file: Unable to locate .mtl file

I have a Python script that can convert .obj files to .json files which can be found here. I attempted to convert messi.obj to messi.js using this script, but encountered the following error message: Couldn't find messi.mtl file Why does the .mtl fi ...

Error Alert - React Hooks: Calling Hook incorrectly

Being new to JS and React, I encountered this error message: Invalid Hook Call when attempting to show and hide a component upon clicking another one. Here is the code snippet that caused the issue: const RenderList = ({data}) => { return data.map(( ...

Exploring the possibility of detecting page scrolling in Javascript by clicking on scroll bars

I have implemented a unique feature on my page that allows users to scroll up and down using custom buttons I created. This functionality is achieved by smoothly transitioning between anchor points on the page using jQuery's animate function. However ...