Perform a function within another function in Vue

I am dealing with two nested functions in Vue. The parent function needs to retrieve the value of an attribute, while the child function is responsible for using this attribute value to make an API call. How can I ensure that both parts are executed simultaneously to fetch the attribute and initiate the API call at once?

//button containing the desired attribute
    <button :data-post-id="My id">Click Me</button>
   //Triggering the parent function 
        <button @click="getPostId">Submit to api</button> 

Javascript

getPostId: function (evt) {
                    const postId = evt.target.getAttribute('data-postid');
                    //console.log(postId);
                    function usePostId(){
                      console.log("I am accessible here " +postId)//null  
                    }
                    return usePostId()


                }

Answer №1

Your method of creating functions repeatedly may lead to unnecessary complexity. It is advisable to begin with a simple function and keep it separate from other functions.

new Vue({
  el: '#app',
  data: {
    postid: ''
  },
  methods:{
    setPostId: function (id){
      this.postid = id;
    },
    getPostId: function () {
      console.log(this.postid);
    }
  }
})
<script src="https://npmcdn.com/vue/dist/vue.js"></script>
<div id="app">
  <button @click="setPostId(11)">Set 11</button>
  <button @click="setPostId(22)">Set 22</button>
  <button @click="setPostId(33)">Set 33</button>
  <button @click="getPostId">Get postid</button> 
  <div>{{postid}}</div>
</div>

Answer №2

Although I don't claim to be a Vue expert, I can definitely point out an inconsistency.

It appears that you are binding your callback to the child element, but setting the attribute data-post-id on the parent element and then expecting the child to have that attribute. Additionally, it seems like there is a mismatch between the attribute names you have set and what you are trying to retrieve.

Regarding the original issue, I'm not entirely sure why you didn't add the attribute to the child element as well. If that's not possible, you may need to locate the desired parent element through the DOM.

Answer №3

@mots here is a possible solution for you:

retrievePostId: function(id) {
  console.log("This code snippet has access to postId " + id)
},

extractPostId: function(evt) {
  const postId = evt.target.getAttribute('data-post-id')
  const result = this.retrievePostId(postId)
  return result
}

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

In search of inspiration to create a recipient list similar to Gmail using Vue3?

Recently, I've been trying to create a recipient list similar to that in Gmail using Vue3 but I'm stuck and unable to find helpful resources online. recipient list I have an array of email addresses that I can loop through and display in a div. ...

Add an array into an object using $set (properties remain unchanged)

I have an object with the following structure: obj: { 1: { 'a': [ [] ], 'b': [ [] ] } } Now, I am attempting to append 'c' => [ [] ] to this object in a watcher. My first attempt was using this.obj[1][&apo ...

Trouble displaying background image in Electron Application

When I try to load an image file in the same directory as my login.vue component (where the following code is located), it won't display: <div background="benjamin-child-17946.jpg" class="login" style="height:100%;"> A 404 error is popping up: ...

`The functionality of parent.location is not operating as expected in Firefox and Chrome, however, it is functioning

Issue with JSP: <A NAME="CustomerInformation"></A> <table class="SectionHeader1"> <TBODY>enter code here <tr> <td>Customer Information</td> </tr> </TBODY> </table ...

What is the process for transforming promises into async await syntax?

login() { return new Promise((resolve, reject) => { userCollection.findOne({email: this.data.email}).then((myUser)=>{ if (myUser && myUser.password == this.data.password) { resolve("Congrats! Succe ...

Missing 'body.append' slot in Vuetify DataTable element

When I tried to add the 'body.append' slot to a data table, I expected the contents to be appended to the end of the body section. However, for some reason it does not show up as expected. <v-data-table> <template slot="body" ...

The method item.appendChild does not exist as a function

Despite being a common error, I've researched extensively and still can't figure out why it's happening. It seems like it should be an easy fix, but I'm struggling to find the solution on my own. var item = document.createElement("div" ...

How can I adjust the animation speed for ChartJS graphics?

Trying to adjust the animation speed of a pie chart in chartJS. Various methods have been attempted: numSteps: Number animationSteps: Number Chart.defaults.global.animationSteps = Number However, none of these approaches have successfully altere ...

The positioning of the input is being altered by the bootstrap-vue formatter

Is there a way to replace whitespaces with underscores in the file name input of bootstrap-vue without changing the cursor position? If I add a white space not at the end of the input, the formatter moves the cursor to the end. How can I achieve this? I a ...

Incorporating an HTTP-based IFRAME into an HTTPS web address

My situation involves a PHP application running in HTTPS mode, within which there is an iframe containing an HTTP file. Both the parent and the iframe exist within the same domain. Strangely, I am unable to access the iframe source using HTTP. Is there a ...

Retrieving the current day integer from a fullcalendar rendering in JavaScript and utilizing it as an array key

I am currently working on rendering a full calendar and I would like each cell to be displayed in a different color based on an array that contains color values for each day of the month. The array is retrieved in JSON format. Here is an example JSON arra ...

Implementing promises in my MEAN stack application

I have developed a controller that performs a Bing search based on the user's input in the URL. After testing the controller with console.log, it seems to be functioning correctly and I have set the variable to return the results. However, when trying ...

Experiment with erroneous scenarios using React, Jest, and React-Testing-Library

I've encountered an issue with a React component that triggers an Error when there is faulty programming. Specifically, the Component requires a prop called data, and I have the following code snippet in place to check for its existence: if (!data) { ...

What are the steps to transform an object containing arrays into strings and then embed them into my HTML code?

Here is the code I need to add to my errors array and send the values to my HTML client-side template: { "email": [ "user with this email already exists." ] } I am looking for something like this: "user with t ...

Is VueJS2 using the computed property/method to modify Vue data?

My form in Vue is almost complete, but I'm facing an issue with an array that seems to be affecting my Vue.data object directly. Here's the situation: In my code, I have a method called getParams() which returns an object containing all the data ...

What could be the reason why the navbar ul li a instance is not appearing in Bootstrap 4 modal when using an

Can anyone help me solve the issue I'm having with viewing HTML in a Bootstrap 4 modal? Everything shows up except for the navbar ul li a elements. I've searched for a solution everywhere, but haven't found one yet. Please assist! (I want t ...

Utilize CountUp.js to generate a dynamic timer for tracking days and hours

I am looking to create a unique counter similar to the one featured on this website https://inorganik.github.io/countUp.js/ that counts up to a specific number representing hours. My goal is to display it in a format such as 3d13h, indicating days and hour ...

Combining two arrays with varying lengths based on their values

Seeking assistance with a programming task that is straightforward yet challenging for me. There are two arrays: one long and one short. var arrayShort = [ { id: 'A', name: 'first' },{ id: 'B', name: &ap ...

I used npm to install a package, but for some reason, it's not appearing in

When attempting to install jquery using npm, I entered the following command: npm install jquery However, upon opening the destination folder, it was empty. (The below text was copied from cmd) > C:\Users\mandar\Desktop\Mady> ...

`sendNodejs header not being transmitted during connection``

My nodejs application utilizes stomp to connect to a server using websockets. However, I am encountering an issue where the application is failing to send the headers that I have specified. Despite referring to clear documentation and examples on how to in ...