Transfer a function from a parent component to a listener in a child component within a Vue environment

I have a scenario where I have a button in my parent component App.vue that triggers an event on a child component, passing an incremental number each time the button is clicked. Currently, I am achieving this by passing the value as a prop and watching for changes in the child component using watch: {

While this method works well, as a newcomer to Vue.js, I am curious if there is a more efficient or recommended way to accomplish this?

App.vue

<template>
  <div id="app">
    <button @click="myMethod">To child</button>
    <Mycomponent :myProp="count" />
  </div>
</template>

<script>
import Mycomponent from "./components/Mycomponent";

export default {
  name: "App",
  components: {
    Mycomponent
  },

  data() {
    return {
      count: 0
    };
  },
  methods: {
    myMethod() {
      this.count++;
    }
  }
};
</script>

Mycomponent.vue

<template>
  <div>
    {{myNumber}}
  </div>
</template>
<script>

export default {
  name: "Mycomponent",
  props: {
    myProp: {
      type: Number
    }
  },

  data() {
    return {
      myNumber: 0
    };
  },

  watch: {
    myProp: {
      deep: true,
      immediate: true,
      handler(newValue) {
        try {
          console.log("Print my value in the consule: ", newValue);
          this.myNumber = newValue
        } catch (err) {
          console.log("no data yet ...");
        }
      }
    }
  }
};
</script>

UPDATED EXAMPLE FOR REACHING PROP IN CHILD COMPONENT

<template>
  <div>
// what if I dont want to display myProp in the template? Just store the data
    {{myProp}} 
    <button @click="myMethod">Method</button>
  </div>
</template>
<script>
export default {
  name: "Mycomponent",
  props: {
    myProp: {
      type: Number
    }
  },
  methods: {
    myMethod() {
      console.log("print myProp ", this.myProp);
    }
  }
};
</script>

But what about if I don't want to display the value. Just use the prop as data?

Answer №1

The watcher is not necessary in this case. Props inherently trigger reactivity, allowing the child component's template to automatically re-render whenever {{ myProp }} is referenced and the button is clicked.

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

Retrieving all raw data in jqGrid: Issues with accessing nested objects

In my grid, the data is structured as follows: Within the rows (0,1,2 and 3 objects), there are additional objects. Of particular note is an object called 'datosPersonales' ('personalData') which contains sub-objects like nombre (name) ...

Is there a way to navigate directly to a specific section without triggering scroll behavior? Are there any alternatives to scrollIntoView() that do not

I'm currently working on setting up a page redirection to a specific section, aiming to navigate to a particular anchor div without any scrolling behavior. However, I've encountered an issue with the #id method due to having a query string in the ...

What are the steps for sending a POST request with custom headers?

Currently, I am attempting to make a post request: For this request, I require a body that looks like this: { "listSearchFields": { "email": "sample" } } When testing this in Postman, it works fine. However, when trying to implement this code in ...

Exploring the differences between leveraging RxJS fromEvent and @ViewChild versus using the keyup event and RxJS Subject to detect changes in input

I have a simple component that allows users to search using the values typed into a search box. I've come across two different ways to implement this functionality and both seem to work well. Method 1 utilizes fromEvent from RxJS to create an observa ...

Pagination does not refresh when conducting a search

HTML Code: The following HTML code displays a table with a search filter. . . <input type="search" ng-model="search.$" /> <table class="table table-striped table-bordered"> <thead> <tr> <th><a href ...

Can a form be selected and submitted using only its class as a selector?

When trying to select and submit a form using only the class as a selector, I encountered an issue: $("form.class").submit(...) doesn't seem to work... however: $("form#id").submit(...) works perfectly fine. Any idea what could be causing this di ...

Functionality of retrieving arrays from PHP via jQuery ajax (JSON) runs smoothly, however encounters issues specifically on web server

No solutions have been able to solve the problem at hand despite finding similar questions. function loadProject(id) { $.ajax({ url: 'loadDrumsetData.php', type: 'GET', data: { i: id }, ...

Starting point for Angular 2 app setup

What is the best way to handle data initialization in my app? For instance, if a user logs in and presses F5, I need to retrieve the current user data from the server before any other queries are executed, such as getting the user's orders. In Angular ...

Tips for adjusting the size of Material UI icons

My Material UI icon size doesn't align naturally with the button: https://i.sstatic.net/l1G98.jpg Button code snippet: <Button variant="outlined" startIcon={<FacebookIcon />}> </Button> Here is the complete example ...

Using AngularJS date picker to set value in Spring model setter

When using AngularJS with Spring, I noticed a discrepancy in the date values between my view file and the POJO User object. In my view file, I have used an input type date to bind the "user.dateOfBirth" attribute. When I select a date, it is displayed cor ...

Ways to create sidebar images in a dual-column layout

I am currently working on creating images for my sidebar that have the same width but different heights. I am trying to achieve this without any spaces between the images. To get a better understanding of what I am trying to do, please refer to the follow ...

Retrieve the file by utilizing the HTML obtained from the AJAX request

Currently, I am attempting to accomplish the task of downloading a file on the same page utilizing HTML generated from an AJAX call. The AJAX call is structured as follows: $.ajax({ url: './x ...

Is it possible to caution users before refreshing the page, while still allowing them to

I have a script that displays a warning message to the user when they attempt to refresh the page. It works perfectly for that purpose. However, my issue is that this same alert pops up when a user clicks on a button or a link within the website itself. I ...

Executing npm / http-server script

I'm currently working on a shell script that will compile an Angular app using the "ng build" command and then launch a web server to host the app from the dist folder. The web server will be started with the "http-server" command, which needs to be i ...

Access the 'from' path from Vue Router within a component

Is there a way to retrieve the previous route within a component without using router.beforeEach in router/index.js? I need to display different DOM elements depending on where the user navigated from to reach the current route. Although console.log(this ...

When the focus() method is used to programmatically set the cursor in a JQuery input element, the blinking cursor does

I have a situation where I have two sibling divs. On the left side, I am loading a PDF document, while on the right side, I have input fields controlled by jQuery. My challenge arises when I try to select and delete the value from the input using the mous ...

Maintain the visibility of the jQuery dropdown menu even when navigating to a different page within the

I am experiencing an issue with my dropdown menu. Whenever I click on a "dropdown link", it opens another page on my website, but the menu closes in the process. I want to ensure that the menu stays open and highlights the clicked "dropdown link" in bold. ...

The route handler is not being invoked

Currently implementing a basic login/logout system using passport.js. Strangely, the router.get('/signout', function(req, res)) is not triggering when attempting to run http://localhost:3000/auth/signout on Advanced Rest Client. Instead, an Inter ...

Facing a problem with Angular JS where the get method is resulting in a 405 error

Hey there, I have a service that is written with the following method: var GetData = function (token) { $http.defaults.headers.common['Authorization'] = 'Bearer ' + token; var response = $http.get(baseurl + "api/controller/sea ...

Issue with loading partial view in CodeIgniter using AJAX

My ajax function is working when trying to load a specific view (createClass.php), but it isn't functioning for other views like classAction.php. script: //--------------this works--------------- $(function(){ $(".classloader").click(function( ...