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

Efficiently convert Map keys into a Set in Javascript without the need to copy and rebuild the set

Even though I am capable of const set = new Set(map.keys()) I don't want to have to rebuild the set. Additionally, I prefer not to create a duplicate set for the return value. The function responsible for returning this set should also have the abili ...

What is the best way to troubleshoot an unresponsive button element to determine the listeners it has?

In a previous situation, I encountered an issue with the event modifier of a nested b-input not working as expected. To resolve this, I had to add .native because I was interacting with a component: b-dropdown(text="Actions") b-drop ...

Could Ramda assist in enhancing pipeline/composition processes with a logging feature?

Considering implementing logging within a composed chain of functions, the following code demonstrates how it can be achieved: const f = R.compose( transformation2, doAlso(x => console.log(`id: ${x.id}`)), transformation1 ) This approach would c ...

Error: Primefaces ajax status failure (dialog has not been defined)

I incorporated the same code found on primefaces.org, specifically this link: http://www.primefaces.org/showcase/ui/ajaxStatusScript.jsf <p:ajaxStatus onstart="statusDialog.show();" onsuccess="statusDialog.hide();"/> <p:dialog modal="true" ...

Having trouble getting Vue components to load in Symfony?

I am integrating Vue into a Symfony 4 project and have followed all the guidelines I could find. Despite my efforts, I am unable to display any Vue components - I can't even get a console.log statement to run from my app.js file. This is my app.js co ...

The v-select menu in Vuetify conceals the text-field input

How can I prevent the menu from covering the input box in Vuetify version 2.3.18? I came across a potential solution here, but it didn't work for me: https://codepen.io/jrast/pen/NwMaZE?editors=1010 I also found an issue on the Vuetify github page t ...

Once the "Get Route" button is pressed, I want to save my JavaScript variable into a database

I am seeking to automatically extract data from the Google Maps API and store it in my MySQL database. Specifically, I want details such as source address, destination address, distance, and duration for all available routes to be inserted into my database ...

Strange sequence of results coming from Vue.js

methods: { ShowWindow: function(QueryID) { this.$data.ID = QueryID; if(this.GetData()) { console.log("asdasd") } document.querySelector("#EditWindow").style.visibility = "visi ...

What is the best way to manage Page Refresh using Angular.js?

I recently followed the tutorial at http://scotch.io/bar-talk/setting-up-a-mean-stack-single-page-application This guide went over controllers and services using angular.js for a single-page application. However, when I try to directly access /pageName o ...

Error encountered during navigation: navigator has not been defined

I encountered an issue where the page gets redirected upon form submission without triggering the catch block. However, in the backend, I am facing an error stating that the API body is not being executed. Below is the code snippet of the page: "use cl ...

Disregard the instructions upon loading the page

I've implemented a directive to automatically focus on the newest input field added to my page. It works well, but there is one issue - when the page loads, the last input is selected by default. I want to exclude this behavior during page load and in ...

Implement auto partial page refreshing in ASP.NET without using the UpdatePanel feature

Looking to implement auto partial page refresh in asp.net without sending excessive data through UpdatePanel. Considering using a webservice called by JavaScript instead, but unsure how to trigger it automatically rather than by button click event. Many e ...

What causes the discrepancy in results between the quoted printable encoding operation in JavaScript and Oracle?

Programming Languages: // JavaScript code snippet //https://www.npmjs.com/package/utf8 //https://github.com/mathiasbynens/quoted-printable par_comment_qoted = quotedPrintable.encode(utf8.encode('test ąčęė')); console.log('par_comment_qot ...

jQuery: Implementing a function for all elements, including those dynamically loaded through Ajax later on

I have implemented a jQuery function to resize text areas, but I need it to work on all text areas. The function works well for existing text areas: $(document.ready(function(){$("text_area").resizer('250px')}); However, it fails to resize tex ...

Shifting divs to different positions upon clicking

I am currently working on a project where I have three divs in a container positioned next to each other. My goal is to make them change their positions when clicked. For example, clicking on the left div should move it to the center position. Here is my p ...

Securing JSON-based RESTful services

I am in the process of developing a web application, where I have established a clear separation between my "frontend" server using Lighttpd to serve index.html and javascript. My frontend, powered by Backbone.js, is connected to my Node.js backend webser ...

Combining two items from separate arrays

How can I efficiently merge objects that share the same index in two different arrays of objects? Below is the first array const countries = [ { "name": "Sweden", "nativeName": "Sverige" }, ...

The NetSuite https.post() method is throwing an error that reads "Encountered unexpected character while parsing value: S. Path '', line 0, position 0"

I'm currently facing an issue when trying to send the JSON data request below to a 3rd party system using the "N/https" modules https.post() method. Upon sending the request, I receive a Response Code of "200" along with the Error Message "Unexpected ...

Tips for avoiding the need to reload a single page application when selecting items in the navigation bar

I am in the process of creating a simple Single Page Application (SPA) which includes a carousel section, an about us section, some forms, and a team section. I have a straightforward question: How can I prevent the page from reloading when clicking on nav ...

Pop-up window for uploading files

Looking for assistance with my file uploading system. I am utilizing a unique purple button from http://tympanus.net/Development/CreativeButtons/ (Scroll down to find the purple buttons). Additionally, I am using a wide, short content popup feature availa ...