Passing the v-model property from a child component to a parent in VueJS

Consider a scenario where there is a Vue component structured like the following:

 Vue.component('child-comp',{
    props:['name', 'val'],
    data: function(){
       return {
           picked: ''
       }
    },
    template: '<div><input type="radio" :name="name" :value="val" v-model="picked"><slot></slot></div>'
});

Additionally, there is a Parent vue instance defined as:

new Vue({
  el: '#app',
  data: {
    message: 'Hello'
  }
});

Within the HTML structure:

<div id="app">
  <child-comp name="fruits" val="apple">Apple</child-comp>
  <child-comp name="fruits" val="banana">Banana</child-comp>
  <child-comp name="fruits" val="cherry">Cherry</child-comp>
  <p>{{ picked }}</p> <!-- this throws an error -->
</div>

The question arises on how to effectively pass the picked property from the child component to the root instance without initiating an $emit event. It seems excessive to trigger an event for accessing a simple property like {{ picked }}. Is there an alternative approach to directly access and display {{ picked }} within <p>{{ picked }}</p>?

Answer №1

If you have a component called child-comp that functions as an input, you can implement two-way props. These props function similarly to v-model, allowing you to utilize them with your custom components.

<custom-input
  :value="something"
  @input="value => { something = value }">
</custom-input>

Learn more about this by clicking here and there. Also, take a look at this thread for additional information. Best of luck!

Answer №2

It's quite simple:

const app = new Vue({
  el: '#app',
  data: {
    message: 'Hello',
    picked: 'apple'
  }
});

And here is the child component :

Vue.component('child-comp',{
    props:['name'],
    template: '<div><input type="radio" :name="name" v-model="picked"><slot></slot></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

Ways to conceal or deactivate button controls on videojs?

I am building an application using video.js and Vue. I am looking for a way to hide or disable certain controls like the play button, playback rate, and make the progress bar read-only. In the video.js documentation, I found that using controls: false hi ...

Is there a way for me to duplicate a complex element multiple times within the same page?

As an illustration, let's say I have a social tab located in my header that I would like to duplicate in the footer. This tab is comprised of various buttons with SVG images on top, event listeners linked to button IDs, and CSS styling. One option is ...

What is the best way to integrate a VueJS application into an already established web page?

Working on a project involves fixing issues with legacy components in a server-rendered web page. I proposed rewriting these parts in Vue to facilitate our migration, and the team approved. I created a mini-app using the Webpack template from Vue CLI, whi ...

Is there a performance boost when using queue() and filter() together in jQuery?

I'm currently refactoring some Jquery code and I've heard that chaining can improve performance. Question: Does this also apply to chains involving queue() and filter()? For instance, here is the un-chained version: var self = this, co = ...

Say goodbye to using 'jQuery .load()' with <img> elements inside <a> tags

I have a static HTML page and some other files with the same structure but different content. <div id="textRed" class="scrollbar"> <h1>Header</h1> <p>Lorem Ipsum</p> <a href="images/image1.jpg" data-lightbox ...

Securing Confidential Information in Vue Data Storage

For the last month, I've dedicated my time to learning Vue. However, there's still one question that puzzles me: The web application I'm currently developing allows users to maintain daily diaries for different projects. They should be able ...

"Enhancing User Experience with AngularJS by Dynamically Modifying and Refresh

I'm currently attempting to dynamically add HTML elements using JavaScript with a directive: document.getElementsByClassName("day-grid")[0].innerHTML = "<div ng-uc-day-event></div>"; or var ele = document.createElement("div"); ele.setAttr ...

Tips on retrieving PHP variable values along with HTML response using AJAX in PHP

I am looking to retrieve 2 variables: 1) The total number of records from the mysqli query performed in search_members.php 2) A boolean value indicating whether any results were found Below is the code I have written: <input type="button" value="Sea ...

Why was the express.js boilerplate code created?

As a newcomer to Node and Express, I am curious about the purpose of the boilerplate directories that are automatically generated when setting up an express project. I have searched online for explanations on the significance of these files without much l ...

What is the best way to add multiple Vue components to my Vue page?

Is there a more efficient way to handle multiple imports without having to write them all out individually? import button1 from './components/button1' import button2 from './componnets/button2' import table1 from './componnets/tabl ...

Troubleshooting compatibility issues between ExpressJS's res.render and AngularJS

I'm relatively new to Node.js, Express, and AngularJS. I'm currently working on a basic Sign-in feature that will redirect to another page upon successful sign-in. While I know I can use window.location for the redirection, I'm trying to uti ...

Learn the process of directing to a view in a jQuery AJAX call with Spring MVC

Below is the ajax call I am using: $.ajax({ type: "POST", url: contextPath +"/action", cache:false, dataType: 'text', data: {Id:Id}, success: funct ...

Is there an easier method to utilize ES6's property shorthand when passing an object in TypeScript, without needing to prefix arguments with interface names?

When working with JavaScript, I often find myself writing functions like the one below to utilize ES6's property shorthand feature: function exampleFunction({param1, param2}) { console.log(param1 + " " + param2); } //Usage: const param1 = "param1" ...

13 Helpful Tips for Resolving Hydration Failure Due to Discrepancy in Custom Dropdown Display between Server and UI

Recently, I embarked on a project utilizing the latest version 13 of Next.js with its new app directory feature. As I integrated a custom dropdown into one of my pages, an error surfaced: "Hydration failed because the initial UI does not match what was ren ...

Ways to confirm the presence of specific keys in a JSON:

After successfully converting an excel sheet's content into a JSON format, my next task is to perform some validation on it. The requirement is to ensure that the jsonData variable contains specific keys in a particular order: Breakfast, Lunch, Snack ...

Tips for displaying a placeholder image within the Next.js image component

I am currently facing an issue with displaying images from API calls. To handle situations where there are no images or errors, I have implemented a code snippet which includes a placeholder image. However, the implementation seems to not be functioning as ...

Customize the <td> column based on values and rows. Modify the current jQuery code

This code snippet contains an HTML table that dynamically populates based on the dropdown selection. The script included in the code highlights the best and worst values in the table by changing their background color to green and red, respectively. & ...

Customize cell design in Vuetify according to the type of item

Is it possible to format dynamically created columns based on a specific property? In cases where the item does not have that property, it should default to the standard behavior. Below is an example of what I'm attempting to achieve (though the synt ...

Is it possible to bind a function to data in Vue js?

Can a function be data bound in Vue? In my template, I am trying something like this: <title> {{nameofFunction()}}</title> However, when I run it, it simply displays 'native function' on the page. Any insights would be appreciated ...

Is there a method to obtain specific props for focused tabBar badges to customize the background color accordingly?

Is there a way to specify focused props in tabBarBadgeStyle to customize the background color? options={{ tabBarLabel: "Teams", tabBarBadge: '3', tabBarBadgeStyle: { backgroundColor: ORANGE ...