Vue.js: Triggering a method upon changes within a child component

Is there a way to trigger a method in the parent component from an action on a child component? In my case, I have added a b-country-select component to the parent component and want it to activate the test method when a change occurs. The component loads successfully but nothing happens when there is a change. However, the tester2 model does work.

Component: BCountrySelect.vue

<template>
    <select class="form-control v-model="country">
          <option v-for='data in countries' :value='data.id'>{{ data.name }}</option>
    </select>
</template>

<script>
export default {
  data(){
      return {
          country: 0,
          countries: [{"id":1, "name":"USA"}, {"id":2, "name":"UK"} ]
      }
  },
  methods:{
      getCountries: function(){

        axios.get('/api/getCountries')
        .then(function (response) {
            this.countries = [{"id":0,"name":"- Select Country -"}].concat(response.data);
        }.bind(this));

      },
    },
    created: function(){
     // this.getCountries()
    }
  }
</script>

Parent::

<template>
    <div class="container">
        <div class="form-group">
            <label>Country:</label>
            <b-country-select v-model="tester1" @change="test()"/>
        </div>
        <div class="form-group">
            <label>Country:</label>
            <select class='form-control' v-model="tester2" @change="test1()">
             <option v-for='data in countries' :value='data.id'>{{ data.name }}</option>
            </select>
        </div>
    </div>
</template>

<script>
    export default {
        mounted() {
            console.log('Component mounted.')
        },
        data(){
            return {
                tester1: 0,
                tester2: 0,
                countries: [{"id":1, "name":"USA"}, {"id":2, "name":"UK"} ]
            }
        },
        methods:{
            test: function() {
                console.log('hi there!');
            }
        }

    }
</script>

Answer №1

To emit a change event, do the following:

<select class="form-control vue-model="location" @change="$emit('update', location)">

Within the parent component:

<b-location-selector vue-model="exampleVar" @update="updateLocation"/>

....

   updateLocation: function(newLocation) {
                console.log('Greetings! New Location is:', newLocation);
            }

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

How to access a template variable within a component

I encountered a problem with ng-template. In our table component, we pass parameters using ngTemplateOutletContext as shown below. Depending on the data type, we use different renderers for the cells. Pay attention to the cellvalue parameter, it is crucia ...

dynamically setting data-bind with javascript

I made changes to an HTML element using JavaScript: document.getElementsByClassName('newc')[0].innerHTML=document.getElementsByClassName('newc')[0].innerHTML+string; After adding the extra HTML content, I realized that the new part di ...

using spread operator to extract properties from API response objects

Currently undergoing a React/Next course, we recently had to retrieve data from an API that returns a list of objects containing information to populate the page. This task was accomplished using Next's getStaticProps method, passing the data to the ...

update the state of the array containing objects with a new value

Here is a piece of code that I am working on: const [state, setState] = useState( [{id: 1, key:""}, {id: 2, key:""}, {id: 3, key:""}] ) I am trying to update the "key" state in my code. I'm a bit confused at t ...

The CSS files are not loading automatically in my React application using Vite

I am facing an issue with importing css and js files into a view in React using vite. The styles are not loading properly, and I have to keep commenting and uncommenting the imports in my code for them to be recognized when entering the view. Below is a s ...

Client sites are not displaying any data through sockets

My goal is to transmit data using socket.io from my nodejs server to the client. The data I am receiving originates from pusher. I have an express backend and set up my server like this: #!/usr/bin/env node var debug = require('debug')('t ...

In JavaScript, the href action is triggered when navigating to a linked page

We have developed a unique eCommerce CMS that utilizes: <a href="javascript:AddToBasket(3471412104801);">Add to Cart</a> ...to enable adding a product to the cart (referred to as Site A). As we are in the process of creating a separate site ( ...

Tips for How to Put a Delay on Ajax Requests and Display a Progress Bar During Loading

I am using checkboxes in the sidebar. When a user selects a checkbox from the sidebar, it displays the post normally. Is there a way to add a progress bar to delay the Ajax result? This is my Ajax code: <script> jQuery(document).ready(function($){ ...

The Vuex state keeps acting mysterious by claiming to be undefined

Here is my post.js located in src > store > post.js: import Vuex from 'vuex' import Vue from 'vue' import axios from 'axios' Vue.use(Vuex) export default new Vuex.Store({ state: { testState: 'Hello&apo ...

What is the process of programmatically sorting a column in a Material UI DataGrid?

Hey there! I'm currently working on a DataGrid that has a column with a custom header, specifically a Select option. My goal is to have the column sorted in descending order every time a user selects an option from the dropdown menu. renderHeader: (pa ...

Angular - Enhance ngFor index while filtering

I am currently working with a list that utilizes an *ngFor loop in the template: <li *ngFor="let product of products | filterProducts: selectedFilter; index as productId"> <a [routerLink]="['/product', productId]"> {{produc ...

Using forEach to iterate through objects presents challenges when attempting to make changes

What is the reason behind the success of the first modification (when reassigning properties of the object) but the failure of the second modification (when reassigning the whole object)? const arr1 = [ { id: 1, value: 1 }, { id: 2, value: 2 }, ...

Issue encountered while utilizing combineReducers: "Error: The assetsReducer returned an undefined value during initialization."

Issue: The "assetsReducer" has returned an undefined value during initialization. When the state passed to the reducer is undefined, it must explicitly return the initial state, which cannot be undefined. If no value is set for this reducer, consider using ...

Ways to clear TextField status

My question is about a Textfield. In the case where the state is null but the text field value is showing in the Textfield. <TextField style={{ width: '65%'}} id="standard-search" ...

Display a dynamic animation once the user switches to the tab

When a user opens the page in a new tab in the background, CSS animations are triggered before they switch to the tab. Is there a method to display the CSS animation only after the user selects the tab? ...

Is there a simple solution to show script 1 to visitors from the US and Canada, while displaying script 2 to visitors from other countries?

I'm looking for a simple script that can show one script to visitors from the US and Canada, and another script to visitors from other countries. It doesn't have to be perfect, but using a service like seems too complex for me. Is there a stra ...

What is the best way to retrieve a value from a JSON file that has multiple nested levels and returns matches from both objects?

My task involves filtering an array of objects that contain nested arrays, and returning a new array based on matches from both levels. The search is triggered by the (input) event, which executes with every key press. Check out the code on StackBlitz: Sta ...

Choosing the second option is not possible after selecting from the initial drop-down menu

After some investigation, I managed to find a way to display a specific productCategory based on the selection from the first dropdown menu. https://i.sstatic.net/AsLE2.png However, when attempting to choose a productCategory, nothing seems to change. T ...

Tips on linking a condition-reaction to document.querySelector

I am struggling to connect the condition-reactions to the input id of passid. I am unsure where to place the document.querySelector() method in order to link the indexed conditions correctly. Below is the code snippet: <!doctype html> <html> ...

Preserving intricate nesting in a Mongoose schema

I've encountered a problem when trying to save nested subdocuments - I'm not certain if it's because they're not in an array or some other reason. The docs suggest that nested objects should be auto-saved, but that doesn't seem to ...