VueJS: A Closer Look at Parent-Child Communication

I have created two Vue components. The first one is called parent-component:

Vue.component('parent-component',{
        methods: {
            test: function(){
             alert('Option Selected');
            }
        },
        template: `
            <div><slot></slot></div>
        `
});

The second component is named animals:

Vue.component('animals',{
        data: function(){
            return {
                selected: ''
            }
        },
        template: `
            <select @change="selectionChanged" v-model="selected">
                <slot></slot>
            </select>
        `,
        methods: {
            selectionChanged: function(){
                this.$emit('optionselected', this.selected);
            }
        }
 });

Now, let's take a look at my HTML code:

<div id="app">
        <parent-component @optionselected="test()">
            <animals>
                <option>Aardvark</option>
                <option>Bear</option>
                <option>Cat</option>
            </animals>
        </parent-component>
 </div>

I am attempting to pass the selected option from the child component animals to the parent component parent-component. I have emitted the optionselected event from the child component, but for some reason, the parent component is not responding to the event and the method test() is not being executed. Can someone please help me identify what I might be doing wrong here?

For a better understanding of the issue, you can check out the JSFiddle Demo

Answer №1

To begin, make sure to attach the listener to the animals component within your template.

<animals @optionselected="test">

Next, keep in mind that when using slots, the elements inside the slots will be evaluated within the component's scope where they are defined, which is Vue's scope in this scenario rather than the parent-component scope. To enable elements inside a slot to access the containing component's data and methods, you must create a scoped slot. As a result, your parent component structure should resemble this:

<div><slot :test="test"></slot></div>

Update your Vue template as follows:

<parent-component>
  <template scope="{test}">
    <animals @optionselected="test">
      <option>Aardvark</option>
      <option>Bear</option>
      <option>Cat</option>
    </animals>
  </template>
</parent-component>

Review the revised code snippet below:

console.clear()
Vue.component('parent-component', {
  methods: {
    test: function(option) {
      alert('Option Selected ' + option);
    }
  },
  template: `
            <div><slot :test="test"></slot></div>
        `
});
Vue.component('animals', {
  data: function() {
    return {
      selected: ''
    }
  },
  template: `
            <select @change="selectionChanged" v-model="selected">
                <slot></slot>
            </select>
        `,
  methods: {
    selectionChanged: function() {
      this.$emit('optionselected', this.selected);
    }
  }
});
new Vue({
  el: "#app",
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.js"></script>
<div id="app">
  <parent-component>
    <template scope="{test}">
      <animals @optionselected="test">
        <option>Aardvark</option>
        <option>Bear</option>
        <option>Cat</option>
      </animals>
    </template>
  </parent-component>
</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

What is the best way to calculate the total sum of grouped data using mongoose?

I have a collection of log data that I need to work with. [ { "logType":1, "created_at": 2015-12-15 07:38:54.766Z }, .. .. .., { "logType":2, "created_at": 2015-13-15 07:38:54.766Z } ] My task is to group the ...

The Next.js dynamic route in production is displaying a 403 error instead of the expected 404. What might be causing this issue?

Whenever I attempt to access https://site.con/categories/, I am greeted with a 403 Forbidden error. However, if I visit https://site.con/categories/sport, everything works perfectly fine, and all other routes function properly. What could potentially be ca ...

Prevent parent element from triggering double click when double clicking on children element with CSS or jQuery

Check out my project demo here Whenever I double click on a child element, it also triggers the parent element at the same time. I want to prevent this behavior so that only the child element is affected by the double click event. Can anyone provide assis ...

What is the best way to save an object in a temporary variable?

RPGDATA = { turkey: 'Leg', chicken: 'Muffin' } var tempdata = RPGDATA; RPGDATA.turkey = 'NoLeg'; console.log(tempdata); // I'm seeing 'NoLeg' here, but shouldn't it be 'Leg'? consol ...

Restrict Type of Child Element in Vue.js

After exploring various options, I have yet to find a definitive answer on whether this functionality can be achieved using vue.js. Coming from a react background where a similar concept exists, I am interested in implementing... My goal is to restrict th ...

Using a hashtag in the URL to open an HTML <div> element

I have a website with two tabs labeled as Home and Action. When I hover over the Action tab, the URL changes to include #tab_action: https://i.sstatic.net/OOD5S.png Then, when I click on it, the related tab content opens: https://i.sstatic.net/JdcGG.pn ...

Guide on utilizing the eval() function to assign a value to a field passed as a parameter

I am interested in achieving the following: function modifyField(fieldName){ eval(fieldName) = 1234; } In simpler terms, I want to pass a specific field name as a parameter and then assign a value to that field. Can someone guide me on how to accomp ...

"Encountered a problem while setting up the Mailgun webhook to handle both multipart and URL encoded

I have been working on creating a web hook listener for Mailgun, and I encountered an issue when I realized that Mailgun can post webhooks using either multipart or x-www-form-urlencoded content-types. Currently, my code uses Multer to handle multipart b ...

React is unable to identify the `initialValue` attribute on a DOM element

Warning: React is not able to recognize the `initialValue` property on a DOM element. If you intended for it to show up in the DOM as a custom attribute, use `initialvalue` in lowercase instead. If it was mistakenly passed from a parent component, make sur ...

Enhance your MUI treeview by incorporating stylish connecting borders

I've been trying to add borders that connect to the nodes in the mui treeview, but I'm having difficulty with not having a vertical border when it's the last leaf node. It currently looks like this: See border example here. However, it sh ...

To enhance user experience, it is recommended to reload the page once

Hello, I'm looking for a way to automatically refresh the page after submitting an AJAX form. Currently, I have an onClick function that seems to refresh the page, but I still need to press F5 to see the changes I've made. Here's the JavaSc ...

How to showcase Twitter Track API on a website

const twitterRequest = twitter_oauth.post( "https://stream.twitter.com/1.1/statuses/filter.json?track=twitter", access_token, access_token_secret Hello, I have successfully implemented a track to display all the latest tweets containing the word "Twitter" ...

What is the best approach to removing a component by utilizing the children prop in React?

I am currently working on a specific scenario: In my project, I have a component called Foo with a property named bar If the bar property is set to true, then I need to display the Bar component that is nested inside the Foo component If the bar prop ...

Guide on Postman: Tracking the number of occurrences for a particular object in a JSON reply

I am just starting out with JSON and Postman. I have a simple task in mind. I have set up a GET request that will return a JSON response like the one below. In this example, I want to extract the count of all "IsArchived" attributes in the response. The ...

Converting a multipart form data string into JSON format

Can you help me figure out how to convert a multipart form data into a JSON object in Node.js? I've been looking for the right module but haven't had any luck so far. Here is an example of my form data: ------WebKitFormBoundaryZfql9GlVvi0vwMml& ...

Vue - Unable to navigate to a different route

I just started working with Vue and attempted to redirect '/home' to '/travel', but for some reason it's not functioning correctly. Can someone please guide me on how to achieve this? What could be the issue with my code? Thank y ...

Trouble with installing Enmap due to better-sqlite3 error

For a while now, I've been struggling to get enmap installed. Despite searching the web exhaustively, I haven't come across any solutions that work for me. Every time I try npm i enmap, I consistently encounter this frustrating error: One part o ...

PHP - Issue with submitting form data using $_POST from within a Div text container

Having some trouble with the submission of the "about_me_container" div in my form using $_POST. I know that divs are not typically used with $_POST, so I tried changing the div to input type="text" and textarea but it still won't work. I also attempt ...

Scroll positioning determines the height of an entity

Here's a code snippet I'm working with: HTML: <div id="wrap"> <div id="column"></div> </div> CSS: #wrap { display: block; height: 2000px; width: 400px } #column { display: block; height: 20px; ...

Passing a variable from Twig to VueJS in Symfony 2.8 and VueJS 2: A beginner's guide

My Symfony 2.8 application now includes VueJs 2 as the front-end framework for added flexibility. Although my application is not single page, I utilize Symfony controllers to render views which are all enclosed in a base Twig layout: <!DOCTYPE html> ...